首页 新闻 会员 周边

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

0
悬赏园豆:10 [已解决问题] 解决于 2017-12-22 15:59

例如:

 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对象数据库已经有了。

报错了。。

 

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

摇啊摇啊摇的主页 摇啊摇啊摇 | 菜鸟二级 | 园豆:408
提问于:2015-06-05 17:08
< >
分享
最佳答案
0

 [ForeignKey("关系外键")]

public virtual Department department{ get; set; }  试下

收获园豆:4
PingMac | 初学一级 |园豆:32 | 2015-06-06 16:58
其他回答(3)
0

既然是新增Employee,为什么是获取一个已存在的Department去插入,而不是实例化一个新的Department?

收获园豆:2
netqiang | 园豆:405 (菜鸟二级) | 2015-08-17 16:35
0

你为什么是查出数据库中已经有的又把他插入进去?这是什么意思?

收获园豆:2
Sky_Fly | 园豆:280 (菜鸟二级) | 2015-11-17 09:19
0
public class Employee 
{
    public virtual Department Department { get;set;}
}

public class Department
{
    public virtual ICollection<Employee> Employees { get; set; }
}

// Insert
var department = dbContext.Departments.FirstOrDefault(x => ...);
if (department != null)
{
    department.Employees.Add(new Employee() { });
}
dbContext.SaveChanges();

你试试行不行?

还有,贴代码的时候最好贴完整点,不然不好分析问题。

收获园豆:2
Jerry Tong | 园豆:385 (菜鸟二级) | 2015-12-30 13:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册