[英]EF Code First: Only set the foreign key(ID) and get a null collection of navigation property
[英]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.