插入引用现有记录的新行的 Linq 问题

时间:2023-02-04
本文介绍了插入引用现有记录的新行的 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-to-SQL 类,StateCounty,其中 County 有一个 FK 到 State.这是一些测试代码:

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'中插入重复键".

换句话说,这里似乎发生的事情是,尽管我已将 s 作为现有记录加载,但当我尝试插入 c 时,Linq 假设所有相关的对象,包括State,也需要插入!

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(...) 函数是否使用与 MyDataContext.GetTable<County>()?

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