如何在TPT映射中更新Entity Framework中的依赖表

时间:2014-02-10 07:11:56

标签: c# entity-framework entity-framework-5 table-per-type

我有这个型号:

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; }
}

和这个背景:

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");
    }
}

我希望能够先插入Student的实例而不使用代码,然后在以后的某个时间点,我想更新Student的代码。这是一个简单的代码说明:

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();
}

问题是,EF投诉应提供FirstNameLastName且不能为空。我可以从Student属性中填充Person继承的属性,但这听起来很臭。 EF中是否有任何方法或技术可以单独更新派生类(依赖表)?

2 个答案:

答案 0 :(得分:3)

这很简单。当您修改状态student2时,实体框架认为FirstNameLastName为空。 而是使用:

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

您应该更改Property

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

答案 1 :(得分:2)

试试这个:

using (var context = new Context())
{
    var student2 = context.Students.SingleOrDefault(x=>x.Id == yourID);

    student2.Code = "Something";

    context.Students.Attach(student2);
    context.Entry(student2).State = EntityState.Modified;
    context.SaveChanges();
}