本文介绍了LINQ的问题,插入有对现有记录的引用新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我相信这是同样的问题的,但没有答案,我想我可以更好地在这里表达的问题...)

(I believe this is the same problem as this one, but there's no answer there, and I think I can express the problem better here...)

我有两个LINQ到SQL类,国家,其中有FK到国家。下面是一些测试代码:

I have two Linq-to-SQL classes, State and County, where County has a FK to State. Here's some test code:

State s = State.GetState("NY"); // here I do a load of a State class via the Linq DataContext
County c = new County();
c.Name = "Rockland";
c.State = s;
MyDataContext.GetTable<County>().InsertOnSubmit(c);
MyDataContext.SubmitChanges(); // throws an exception



引发的异常是PRIMARY KEY约束违反PK_State'。不能插入对象dbo.State'重复键。

在换句话说,这似乎在这里发生的是尽管已经载入我的取值为现有的记录,当我试图插入 C ,LINQ的是假设所有相关的对象,国家在内,还需要插入!

In other words, what appears to be happening here is that despite my having loaded s as an existing record, when I attempt to insert c, Linq is assuming that all related objects, State included, also need to be inserted!

这是完全荒谬的,我不认为微软会作出如此巨大的错误 - 所以它必须在某个地方我自己的理解是错误的。

This is completely absurd, and I cannot believe that Microsoft would have made such a huge blunder - so it must be that somewhere my own understanding is faulty.

任何人都可以请解释什么,我做错了,什么正确的方法这里是?

Can anyone please explain what I am doing wrong, and what the correct approach here is?

谢谢!

推荐答案

State.GetState(...)使用相同的datacontext为 MyDataContext.GetTable< 功能;县及GT;()

Is the State.GetState(...) function using the same datacontext as MyDataContext.GetTable<County>()?

这篇关于LINQ的问题,插入有对现有记录的引用新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:10