簡體   English   中英

EF 7 beta 6:在EF 7中具有一對多關系的實體

[英]EF 7 beta 6 : Entities with one to many relationships in EF 7

我有一個非常簡單的模型:

class Bag
{
    public int Id { get; set; }
    public ICollection<RandomThing> RandomThings { get; set; }
}

class RandomThing
{
    public int Id { get; set; }
    public String Description{ get; set; }
}

我上下文的OnModelCreating (在EF 6中 )類似於:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Bag>()
        .ToTable("Bag")
        .HasMany(x => x.RandomThings).WithRequired(x => x.Bag).WillCascadeOnDelete();

    modelBuilder.Entity<RandomThing>().ToTable("RandomThing");
}

據我所知,沒有等效的方法可以做到這一點。 我知道不支持級聯刪除 但是,我想知道,對我的代碼示例中定義的一對多關系進行建模的最佳方法是什么? 似乎所有這些東西都已消失(或尚未實現)。

我已經看到了一個DbContext的示例( 在這里 ),它與我想要的完全一樣,但是實際上是錯誤的,並且不起作用。 如果我嘗試提取該源代碼,設置環境並在帶有帖子的博客實體上進行保存,則這些帖子不會像人們想象的那樣被保存。

有什么解決方法嗎?

更新 :此答案是針對EF7 beta7編寫的。 此后,API發生了變化。 有關使用EF Core的最新信息,請參見http://docs.efproject.net/en/latest/modeling/relationships.html

原始答案

在EF 7中,您可以在OnModelCreating方法中配置一對多關系。 為此,請向RandomThing添加一個屬性以表示外鍵,並向父類型添加CLR引用。

class Bag
{
    public int Id { get; set; }
    public ICollection<RandomThing> RandomThings { get; set; }
}

class RandomThing
{
    public int Id { get; set; }
    public String Description{ get; set; }

    public Bag Bag { get; set; }
    public int BagId { get; set; }
}

在您的上下文中,使用以下設置配置關系:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{  
    modelBuilder.Entity<RandomThing>()
        .Reference(e => e.Bag)
        .InverseCollection(p => p.RandomThings)
        .ForeignKey(e => e.BagId);
}

旁注 :當EF 7 計划添加支持通過屬性進行配置時。

盡管我根本沒有使用過EF7,但在EF6中,我會讓您的模型看起來像這樣:

class Bag
{
    public int Id { get; set; }
    public virtual ICollection<RandomThing> RandomThings { get; set; }
}

class RandomThing
{
    public int Id { get; set; }
    public String Description{ get; set; }

    public int BagId {get; set;}
    [ForeignKey("BagId")]
    Public Bag Bag {get; set;}
}

這樣,就可以通過數據注釋來處理關系,並且您不需要為此特定任務使用model builder

暫無
暫無

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

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