Asp.net-Mvc

如何首先使用 EF 核心程式碼製作連接表

  • October 28, 2021

我有這三個模型:

public class Card
{
   public int ID { get; set; }
   public string Name { get; set; }
   public string Class { get; set; }
   public string Image { get; set; }
}

public class Deck
{
   public int ID {get; set;}
   public string Name {get; set;}
   public string Class {get; set;}
   public virtual ICollection<DeckCard> DeckCards {get; set;}
}

public class DeckCard
{
   public int ID {get; set;}
   public int DeckID {get; set;}
   public int CardID {get; set;}
}

我想本質上將 DeckCard 模型用作連接表。我需要能夠在我的 DecksController/Index 視圖中填充它。誰能給我指導或指出正確的方向?

請注意,卡片表是一個靜態表(我不知道這是否是正確的術語,但它會被遊戲目前擁有的任何卡片填充並保持不變(這是一個套牌建構網站))。

**第一的。**您無需為一對多關係創建模型(DeckCard),以便 EF 自動在您的數據庫中創建此表。

**第二。**在 DbContext 類中添加或覆蓋OnModelCreating方法 例如:

MyApplicationDbContext.cs

public class MyApplicationDbContext : DbContext
{
    public DbSet<Card> Cards { get; set; }
     
    public DbSet<Deck> Decks { get; set; }

    //This is the Model Builder
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    { 
          modelBuilder.Entity<Card>()
               .HasRequired<Card>(_ => _.Card)
               .WithMany(_ => _.Deck);
               
    }

}

甲板控制器.cs

public ActionResult Index()
{ 
     var model = context.Card.AsNoTracking().Include(_ => _.Decks).ToList(); 
       
     return View(model);
}

對於帶有急切載入的連接查詢,請使用Include();

另外,請參見下面的連結:

從 Entity Framework 6 中獲得更多性能

實體框架載入相關實體

配置一對多關係

EF Core 中的關係

引用自:https://stackoverflow.com/questions/41535157