我有这个型号:
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投诉应提供FirstName
和LastName
且不能为空。我可以从Student
属性中填充Person
继承的属性,但这听起来很臭。 EF中是否有任何方法或技术可以单独更新派生类(依赖表)?
答案 0 :(得分:3)
这很简单。当您修改状态student2
时,实体框架认为FirstName
和LastName
为空。
而是使用:
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();
}