Friday, 14 March 2025

Entity Splitting in Entity Framework Core

We will see how to have an entity with some fields come from different table or view. EF Core used in this writing is version 9.0.0.

We have Student entity:
public partial class Student
{
    // these fields come from Student table
    public long StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string StudentNumber { get; set; }
}
Then we would like to add a few fields that come from a different view:
// to have these fields from ViewStudentDetails
public string Email { get; set; }
public string Address { get; set; }

First, we create another Student partial class so that it is not overwritten whenever we run scaffold command again. We could name the file 'Student_Partial.cs'.
public partial class Student
{
    public string Address { get; set; }
    public string Email { get; set; }
}

Then create another partial database context file (name it 'Partial_StudentContext.cs') if we don't have one already. Then add these configurations in OnModelCreatingPartial method:
public partial class StudentContext
{
   partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
   {
      modelBuilder.Entity<Student>(entity =>
      {
         entity.SplitToTable("ViewStudentDetails", x =>
         {
            x.Property(e => e.Email).HasColumnName("Email");
            x.Property(e => e.Address).HasColumnName("Address");
         });
      });
   }
}

No comments: