gpt4 book ai didi

c# - EF 代码第一个没有导航属性但具有父集合属性的外键

转载 作者:太空狗 更新时间:2023-10-29 20:19:35 24 4
gpt4 key购买 nike

我的问题类似于this一个,但在这种情况下,我确实在父级上有一个引用子代的集合属性:

public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
public int Id { get; set; }
public int ParentId { get; set; }
}

就像引用的问题一样,我不想/不需要 Child 上的 Parent 属性。

那么应该如何更改以下语法来定义关系?

modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent) <---- no such property "Parent"
.WithMany(p => p.Children)
.HasForeignKey(c => c.ParentId);

最佳答案

您可以使用不带参数的WithRequired方法:

modelBuilder.Entity<Parent>() 
.HasMany(p => p.Children)
.WithRequired()
.HasForeignKey(c => c.ParentId);
如果没有反向导航属性,

With 部分可以留空。

关于c# - EF 代码第一个没有导航属性但具有父集合属性的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42119952/

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