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

Linq problem with inserting new rows that have references to existing records(插入引用现有记录的新行的 Linq 问题)
本文介绍了插入引用现有记录的新行的 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 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)