[英]Why don't I have to update a parent object when updating both the parent and child entity in EF code first
I have two entities (student and studentImage). 我有两个实体(student和studentImage)。 When updating info for student, I get the student and modify data in it.
在更新学生信息时,我得到了学生并在其中修改数据。 If I've modified data from both the student and studentImage why is it that when I go to my repository to update I only have to run the second line here shown below?
如果我同时修改了Student和StudentImage的数据,为什么在我更新存储库时只需要运行下面显示的第二行? And it updates both the student and studentImage rows.
并且它同时更新了student和studentImage行。 you would think I would have to update both or at least the student, but if I try to run both lines of code I get an exception thrown...It seems like when I update student.StudentImage it progagates upward to student?
您可能会认为我必须同时更新两个或至少一个学生,但是如果我尝试同时运行这两行代码,则会引发异常……似乎当我更新student.StudentImage时,它会向上传播给学生吗?
public void Update(Student student)
{
//context.Entry(student).State = EntityState.Modified;
context.Entry(student.StudentImage).State = EntityState.Modified;
}
public void Save()
{
context.SaveChanges();
}
Here are my student and studentImage entities jsut for show. 这是我的student和studentImageEntity实体显示。
public class StudentImage
{
[Key, ForeignKey("Student")]
public int StudentId { get; set; }
public byte[] Image { get; set; }
public byte[] ImageThumbnail { get; set; }
public string ContentType { get; set; }
public virtual Student Student { get; set; } // one-to-one
}
public class Student
{
public int StudentId { get; set; }
public virtual StudentImage StudentImage { get; set; } //one-to-one
[Required]
public DbGeography LocationPoints { get; set; } //37.1234, -122.2342
[Required]
public string Location { get; set; } //ex. San Francisco, CA, USA
[MaxLength(250)]
public string Education { get; set; } //State Univesity
public string Work { get; set; } // Taco Bell, Starbucks
public StudentStatus Status { get; set; }
}
Entity Framework does a pretty good job at determining which records need to be updated when you Save. 实体框架在确定保存时需要更新哪些记录方面做得很好。 It also handles change tracking automatically - you don't even need to mark your entity as modified due to the way it uses proxies.
它还可以自动处理变更跟踪-由于实体使用代理的方式,您甚至无需将实体标记为已修改。
If you Save an entity, it'll look at any associations that the entity depends on and check those for changes also. 如果您保存实体,它将查看该实体所依赖的所有关联,并检查这些关联是否有更改。 After it has determined which records need to be updated/added, it will generate the query that updates these records in a way that will satisfy constraints.
在确定需要更新/添加哪些记录后,它将生成查询,以满足约束条件的方式更新这些记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.