例如:
1 class Employee
2 {
3 Guid Id{get;set;}
4 .
5 .
6 Department department{get;set;}
7
8 }
9 class Department
10 {
11 Guid Id{get;set;}
12 string Name{get;set;}
13 }
14
15 var depart=dbContext.Departments.Find(...);//獲取到一個已存在的Department
16 Employee employee=new {...};
17 employee.department=depart;
18
19 dbContext.Employees.Add(employee)
20 dbContext.SaveChanges();
21
22 會報錯 不能在對象“dbo.Department”中插入重復鍵,違反了主鍵約束。
新增Employee對象的時候 ,EF 會去新增一條Department對象。但這個Department對象數據庫已經有了。
報錯了。。
?
想請問這種情況的正常寫法是怎樣的?
4 回答

慕容森
TA貢獻1853條經驗 獲得超18個贊
public class Employee
{
public virtual Department Department { get;set;}
}
public class Department
{
public virtual ICollection Employees { get; set; }
}
// Insert
var department = dbContext.Departments.FirstOrDefault(x => ...);
if (department != null)
{
department.Employees.Add(new Employee() { });
}
dbContext.SaveChanges();
你試試行不行?
還有,貼代碼的時候最好貼完整點,不然不好分析問題。
- 4 回答
- 0 關注
- 585 瀏覽
添加回答
舉報
0/150
提交
取消