Search code examples
c#entity-frameworkentity-framework-5table-per-type

How to update dependent table in Entity Framework in TPT mapping


I have this model:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Student : Person
{
    public string Code { get; set; }
}

and this context:

public class Context : DbContext
{
    public Context()
        : base("Context")
    {
        Database.SetInitializer<Context>(null);
    }

    public DbSet<Student> Students { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().ToTable("People");
        modelBuilder.Entity<Student>().ToTable("Students");
    }
}

And I want to be able to insert an instance of Student without code first, and then later at some future point, I want to update that Student's code. Here is a simple code explanation:

var student = new Student
{
    FirstName = "Saeed",
    LastName = "Nemati",
};
using (var context = new Context())
{
    context.Students.Add(student);
    context.SaveChanges();
}

// A month later I want to update the code
var student2 = new Student
{
    Id = student.Id,
    Code = "something"
};
using (var context = new Context())
{
    context.Students.Attach(student2);
    context.Entry(student2).State = EntityState.Modified;
    context.SaveChanges();
}

The problem is, EF complaints that FirstName and LastName should be provided and can't be null. I can populate Student inherited properties from Person properties, but this sounds smelly. Is there any approach or technique in EF to update the derived class (dependent table) in isolation?


Solution

  • This is simple.When you modify state student2 entity framework thinks FirstName and LastName are null. Instead using:

    context.Entry(student2).State = EntityState.Modified;
    

    You should change Property:

    context.Entry(student2).Property(x => x.Code).IsModified = true;