简体   繁体   中英

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). 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? And it updates both the student and studentImage rows. 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM