[英]How to update dependent table in Entity Framework in TPT mapping
我有這個模型:
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
應提供和不能為空。 我可以從Person
屬性填充Student
繼承的屬性,但這聽起來很臭。 EF中是否有任何方法或技術可以單獨更新派生類(依賴表)?
這很簡單。修改狀態后, student2
實體框架會認為FirstName
和LastName
為null。 而是使用:
context.Entry(student2).State = EntityState.Modified;
您應該更改Property
:
context.Entry(student2).Property(x => x.Code).IsModified = true;
嘗試這個:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.