如何首先使用EF核心代码制作联接表 [英] How to make a join table using EF core code first

查看:66
本文介绍了如何首先使用EF核心代码制作联接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下三种模型:

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视图中填充它.谁能给我指导或指出正确的方向?

I want to use the DeckCard model as a join table essentially. I need to be able to populate it in my DecksController/Index view. Can anyone give me guidance or point me in the right direction?

请注意,Card表是静态表(我不知道这是否是正确的用词,但是它将填充并且不会更改游戏中当前拥有的任何纸牌(这是一个套牌建造网站)).

Note that the Card table is a static table (I don't know if that's the correct term for it but it will be populated and unchanged with whatever cards the game currently has (it's a deck building website)).

推荐答案

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

First. You Not need to Create model(DeckCard) for one to many relations so that EF Automatic Create This Table In Your Database.

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

Second. Add or override OnModelCreating Method in your DbContext Class For Example:

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);

     }

 }

DecksController.cs

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

      return View(model);
 }

对于具有提前加载的联接查询,请使用Include();

For join query with Eager loading l use Include();

也,请参见下面的链接:

also, see below Links:

从Entity Framework 6中获得更多性能

实体框架加载相关实体

配置One-一对多关系

EF核心中的关系

这篇关于如何首先使用EF核心代码制作联接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆