Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

c# - LINQ to SQL ForeignKeyReferenceAlreadyHasValueException error

This error is being generated when I try to change a foreign key. I know this is a very common error I’ve found tons of information about it and tried to implement the fixes I’ve found but I still get this error when trying to update Keys. Reference Thread

Originally I was just directly assigning the value and not trying to map the entities.

ticket.assigned_to_group = assigned_to

I’ve since changed to try and map the entities which I believe the correct answer; however I still get the error.

ticket.assigned_to_group = db.sub_units.Single(f => f.id == assigned_to).id;

Any idea why this would not work. Also if I have a table with multiple foreign keys, do I really need to do a new query for each key or is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are trying to assign an ID when you need to assign the entity. (I'm not 100% sure this is what you are doing)

// Don't assign just the id
Person.ParentId = parentId;

// Assign the entity
Person.Parent = db.Parents.Single(x.Id == parentId);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...