在EF中 新增带外键的数据 的写法

例如: 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对象数据库已经有了。 报错了。。   想请问这种情况的正常写法是怎样的?
喵喔喔
浏览 532回答 4
4回答

手掌心

[ForeignKey("关系外键")] public virtual Department department{ get; set; }  试下

慕容森

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(); 你试试行不行? 还有,贴代码的时候最好贴完整点,不然不好分析问题。
打开App,查看更多内容
随时随地看视频慕课网APP