简体   繁体   中英

C# Entity Framework 6 loading related entities

I want update the student role by the received role id .

The problem is that if I load the role instance before load the student instance, the entity role is included in the query and the entity was attached automatically and the update fails with this correct integrity message error (bottom).

 using (var ctx = new SchoolContext())
 {
    ctx.Configuration.LazyLoadingEnabled = false;
    var role = ctx.Role.Select(x => x).ToList(); 
    var student = ctx.Students.Include(s => s.Courses)
                              .Where(s => s.Id = id);

    student.RoleId = roleId;
    ctx.SaveChanges();            
 }

Error:

A referential integrity constraint violation occurred: The property value(s) of Role.Id on one end of a relationship do not match the property value(s) of Student.RoleId on the other end.

I explicit use LazyLoadingEnabled = false but it doesn't work. I don't find a way for exclude the role in the query. The only way is load roles after...

Try using the navigation property Student.Role instead of Student.RoleId :

var role = ctx.Role.Single(r => r.Id = roleId);
student.Role = role;

As a general rule of thumb: manipulate entity relations through the navigation properties instead of their foreign key properties.

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