(我相信这与 这个,但那里没有答案,我想我可以在这里更好地表达问题......)
(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 类,State 和 County,其中 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 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么我不应该总是在 C# 中使用可空类型Why shouldn#39;t I always use nullable types in C#(为什么我不应该总是在 C# 中使用可空类型)
C# HasValue vs !=nullC# HasValue vs !=null(C# HasValue vs !=null)
C# ADO.NET:空值和 DbNull —— 有没有更高效的语法C# ADO.NET: nulls and DbNull -- is there more efficient syntax?(C# ADO.NET:空值和 DbNull —— 有没有更高效的语法?)
如何在c#中将空值设置为int?How to set null value to int in c#?(如何在c#中将空值设置为int?)
使用 Min 或 Max 时如何处理 LINQ 中的空值?How to handle nulls in LINQ when using Min or Max?(使用 Min 或 Max 时如何处理 LINQ 中的空值?)
在 C# 中如果不为 null 的方法调用Method call if not null in C#(在 C# 中如果不为 null 的方法调用)