开发者

Many-to-Many insert failing - Entity Framework 4.1 DbContext

I am using DB first method, EF 4.1 with DbContext POCO code gen.

My database has a many-to-many relationship as shown below:

Employee

EmployeeId

EmployeeName

Account

AccountId

AccountName

EmployeeAccount

EmployeeId

AccountId

The problem occurs when I am trying to insert a new Employee, and assign them a pre existing account, so I am basically doing this as below:

Employee emp = new Employee();
emp.EmployeeName = "Test";
emp.Accounts.Add(MethodThatLooksUpAccountByName("SomeAccountName"));

context.Employees.Add(emp);
context.SaveChanges();

The SQL this is executing (incorrectly), is开发者_如何学编程 attempting to INSERT a new [Account] record, and this is failing on a constraint violation. Of course, it should not INSERT a new [Account] record, it should only insert a new [EmployeeAccount] record, after inserting the [Employee].

Any advice? Thanks.


MethodThatLooksUpAccountByName does this method return an attached or detached object? In any case, you may try to attach the object it returns to the context.

Employee emp = new Employee();
emp.EmployeeName = "Test";
var acc = MethodThatLooksUpAccountByName("SomeAccountName");
context.Attach(acc); //I don't remember if it's attach or attachobject, but intellisense should help you there. 
emp.Accounts.Add(acc);

context.Employees.Add(emp);
context.SaveChanges();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜