2015-11-23 101 views
-1

我想更新學生角色收到的角色IDC#實體框架6加載相關實體

的問題是,如果我加載之前加載角色實例學生實例,實體的角色包括在查詢和實體已自動連接並更新失敗,這是正確的完整性消息錯誤(下圖)。

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();    
} 

錯誤:

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.

我明確使用LazyLoadingEnabled = false,但它不工作。我找不到在查詢中排除角色的方法。唯一的辦法是負載角色後...

+0

可以共享學生和角色的實體類的結構? – Dhunt

+0

之前設置'student.RoleId'數據庫上已經存在'roleId'? – Ninita

+0

@Hanc '變種學生= ctx.Students.Include(S => s.Courses) 。凡(S => s.Id = ID);'它應該.'Where(S => s.Id == ID)' – Eldho

回答

0

嘗試使用,而不是Student.RoleId的導航屬性Student.Role

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

作爲一個一般的經驗法則:通過導航性能,而不是他們的外鍵操作實體間關係屬性。