开发者

LINQ to SQl updating primary key field?

开发者 https://www.devze.com 2022-12-25 12:55 出处:网络
I have a linq to sql table/class that uses a GUID as both a primary key and as foreign key. This problem came up when factoring some code that previously worked.

I have a linq to sql table/class that uses a GUID as both a primary key and as foreign key. This problem came up when factoring some code that previously worked.

The exception generated is

"Operation is not valid due to the current state of the object."

The process I use is as such:

aspnet_User user() = new aspnet_User();
aspnet_user.childTable = new childTable();
.. set some properties
user.Insert() -> my cus开发者_Go百科tom method

... @ my custom method

using (mycontext dc = new context() ) 
{
user.childTable.ID = (Guid)myNewlyCreatedGuid;
}

The exception occurs on the assignment childTable.set_UserId().


As long as your model correctly defines the foreign key relationship between the User and the child table, you don't have to manually set the primary key for the child table. I cover the reason why in the accepted answer to this question.


He shows how to do this using a new entity:

http://aspnetking.blogspot.com/2009/03/foreign-key-issue-for-update-in-linq.html

Clearing the reference example:

http://dotnetslackers.com/Community/blogs/bmains/archive/2009/05/21/linq-to-sql-error-foreignkeyreferencealreadyhasvalueexception.aspx

0

精彩评论

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

关注公众号