簡體   English   中英

EF Code First外鍵沒有導航屬性,但具有父集合屬性

[英]EF Code First foreign key without navigation property, but with parent collection property

我的問題類似於這個問題,但在這種情況下,我確實在父母那里引用了childeren的集合屬性:

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部分可如果沒有逆導航屬性是空的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM