c# - 使用 LINQ to SQL 创建查找时出现 ForeignKeyReferenceAlreadyHasValueException

标签 c# .net linq-to-sql

我是 C# 和 .NET 的新手,刚开始学习 LINQ to SQL,我喜欢它。但是.. 我发现这是一件非常烦人的事情。由于“ForeignKeyReferenceAlreadyHasValueException”,实现查找非常复杂!没有简单直接的方法可以做到!我注意到,如果我删除 LINQ 实体之间的所有关联,“ForeignKeyReferenceAlreadyHasValueException”问题就不再存在!我计划开发小型 WinForms 数据库应用程序,不超过 100 个表...

所以我的问题是:

如果我使用 LINQ2SQL 但删除 LINQ 实体之间的所有关联并在数据库中保留关系,我会有什么损失/风险?

最佳答案

基本上你将失去查询支持、延迟加载、IntelliSense 等。例如,如果你删除 UsersQuestions< 之间的关联,你将不会拥有这样的东西/strong>:

from u in context.Users
where u.Questions.Count > 2
select u;

LINQ 的要点是为您提供在 C# 代码中实现关系数据库模型所需的所有构造,使您能够查询该模型。如果删除所有关联/关系,LINQ to SQL 将失去它的用途。

关于 Exception你得到了:

If the association property is assigned a value you cannot change the foreign key field anymore, you must change the relationship by changing the association property. For example, using Customer and Order from Northwind sample database. If the 'Customer' property on an order is assigned a value you can no longer manually change the order's CustomerID field, since it must match the PK of the customer. You can, however, change the 'Customer' property directly, assigning it a new customer instance. This action will automatically update the CustomerID field to match. By Matt Warren (LINQ to SQL architect)

这是您需要做的来解决您的问题:

LINQ to SQL ForeignKeyReferenceAlreadyHasValueException error

对于查找和 LINQ,执行此操作:

LINQ, Lookups, ForeignKeyReferenceAlreadyHasValueException

例如在绑定(bind)组合框时使用此代码:

With cboCategory 
.DataSource = From Category In db.Categories Order By Category.Name
              Select Category 
.DisplayMember = "Name" 
.ValueMember = "ID"    don't set value member: http://tinyurl.com/d9etoy 
.DataBindings.Add(New Binding("SelectedItem", ItemBindingSource, "Category")) 
End With 

关于c# - 使用 LINQ to SQL 创建查找时出现 ForeignKeyReferenceAlreadyHasValueException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3722254/

相关文章:

c# - LINQ 到 SQL : GroupBy() and Max() to get the object with latest date

linq-to-sql - 查询结果不能枚举多次?

c# - 将数组转换为类型数组

.net - SQL中默认的最大事务超时是多少

c# - 为什么我要按位置绑定(bind) OracleCommand 参数?

.net - 帮助调试 "Could not load file or assembly X or one of its dependencies"的提示

c# - ping 子网时程序锁定

.net - Linq to SQL 错误 SQL 不比较 NText、Text、Xml 或 Image?

javascript - 如何从 Javascript 代码在 C# 中进行十进制按位运算

c# - 如何以编程方式删除列?