ITPub博客

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

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

作者:germo 时间:2019-09-03 09:55:59 0 删除 编辑
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对象数据库已经有了。

报错了。。

 

想请问这种情况的正常写法是怎样的?

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1868/viewspace-3153693/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-17

  • 博文量
    209
  • 访问量
    8229