gpt4 book ai didi

linq-to-sql - LINQ 到 SQL : Composite FK only half nullable

转载 作者:行者123 更新时间:2023-12-04 04:48:00 25 4
gpt4 key购买 nike

在使用复合键的 Multi-Tenancy 应用程序中
(例如 SiteId, $(Table)Id )
对于一切,我有以下两个表:

Owner (
SiteId bigint NOT NULL,
OwnerId bigint NOT NULL,
ThingId bigint NULL
)

Thing (
SiteId bigint NOT NULL,
ThingId bigint NOT NULL
)

和来自 Owner (SiteId, ThingId) 的外键至 Thing (SiteId, ThingId) .

如果我写一个这样的方法:
void RemoveThing(Owner owner)
{
owner.Thing = null;
db.SubmitChanges();
}

我得到了异常(exception)
System.InvalidOperationException: An attempt was made to remove a relationship between a
Thing and a Owner. However, one of the relationship's foreign keys (Owner.MultiId,
Owner.ThingId) cannot be set to null.
at System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.SynchDependentData()
at System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list)
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()
at proj.Program.RemoveThing() in C:\proj\Program.cs:line 115

为了解决这个问题,我可以添加 SiteId 的第二个副本。 (也许 ThingSiteId)到 Owner表。但它只会等于 SiteId,所以我会花费数据库大小和架构复杂性来解决我的 ORM。

怎么告诉LINQ to SQL不用担心那一半的外键关系,只设置 Owner.ThingId=NULL ?

最佳答案

套装ThingId = null而不是 Thing = null .不要重复使用您的 DataContext ,否则您可能会收到“外键已设置”异常。

LINQ 正在积极防止这变得更容易。在 ChangeTracker.SynchDependentData() ,检查每一列是否属于任何关联的一部分,然后如果该列是

  • 设置为空
  • 关联有任何不可为空的列(!)

  • 在我看来,这是 LINQ-to-SQL 中的一个错误。

    关于linq-to-sql - LINQ 到 SQL : Composite FK only half nullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889267/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com