如何首先使用EF核心代码创建连接表

toc*_*ool 5 asp.net-mvc entity-framework-core

我有这三个模型:

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;}
}
Run Code Online (Sandbox Code Playgroud)

我想基本上使用DeckCard模型作为连接表.我需要能够在DecksController/Index视图中填充它.任何人都可以给我指导或指出我正确的方向吗?

请注意,Card表是一个静态表(我不知道它是否是正确的术语,但它将填充并保持游戏当前具有的任何卡(它是一个甲板构建网站)).

Soh*_*deh 8

第一.您不需要为一对多关系创建模型(DeckCard),以便EF在您的数据库中自动创建此表.

第二.OnModelCreating在DbContext类中添加或覆盖方法例如:

MyApplicationDbContext.cs

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

     public DbSet<Deck> Decks { get; set; }

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

     }

 }
Run Code Online (Sandbox Code Playgroud)

DecksController.cs

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

      return View(model);
 }
Run Code Online (Sandbox Code Playgroud)

对于加入查询与Eager加载 l使用Include();

另外,见下文链接:

从Entity Framework 6中获得更多性能

实体框架加载相关实体

配置一对多关系

EF Core中的关系