gpt4 book ai didi

c# - 无法创建级联外键

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:05 25 4
gpt4 key购买 nike

我有一张文件表:

public class Document
{
[Key]
public int DocumentId {get; set;}
public string Title {get; set;}
}

我还有一张 DepthDocuments 表:

public class DepthDocument
{
[Key]
public int DepthDocumentId {get; set;}
public int DocumentId {get; set;}
public int Depth {get; set;}
}

每个文档都有对应的深度文档。两个表的行数相同。我试图告诉 EF - 当我删除一个文档时 - 我也想删除相应的 DepthDocument。我认为其中一部分是创建 1-1 关系,我已经尝试将其添加到 Document 类中:

    [Required]
public virtual DepthDocument DepthDocument { get; set; }

然后是:

modelBuilder.Entity<Document>()
.HasRequired(c => c.DepthDocument).WithRequiredPrincipal()
.WillCascadeOnDelete(true);

但是我得到:

Cascading foreign key 'FK_dbo.DepthDocument_dbo.Document_DepthDocumentId' cannot be created where the referencing column 'DepthDocument.DepthDocumentId' is an identity column.

我做错了什么?

更新:

我有 DocumentId 和 DepthDocumentId 列,因为我现在正在创建 DepthDocument 表,我需要在种子方法中为每个文档创建一个新的 DepthDocument:

foreach (var document in context.Documents.ToList())
{

context.DepthDocuments.AddOrUpdate(
d => d.DocumentId,
new DepthDocument()
{
DocumentId = document.DocumentId, // can I do this? I tried and ran into problems with missing entries not getting added
// other props
});
context.SaveChanges();
}

最佳答案

DepthDocument 更改为如下所示:

public class DepthDocument
{
[Key]
public int DocumentId {get; set;}
public int Depth {get; set;}
}

因为它是 1:1 的关系,并且 DepthDocument 不能在没有匹配的 Document 的情况下存在,所以没有任何理由需要 DepthDocument使用不同的 key 。

关于c# - 无法创建级联外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17767975/

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