插入引用现有记录的新行的 Linq 问题
- 作者: 夢De预見
- 来源: 51数据库
- 2022-12-13
问题描述
(我相信这与 这个,但那里没有答案,我想我可以在这里更好地表达问题......)
(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>()?
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
