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

时间:2017-01-08 16:50:20

标签: 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;}
}

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

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

2 个答案:

答案 0 :(得分:8)

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

其次。在DbContext类中添加或覆盖OnModelCreating方法例如:

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

另见,见下文链接:

Getting more performance out of Entity Framework 6

Entity Framework Loading Related Entities

Configure One-to-Many Relationship

Relationships In EF Core

答案 1 :(得分:2)

使用您当前的实体结构,您可以在所有三个数据集之间编写连接,然后在DeckId上执行分组并派生结果。

我会为我的视图为这个分组数据表示创建2个视图模型类。

public class DeckVm
{
    public int Id { set; get; }
    public string Name { set; get; }
    public IEnumerable<CardVm> Cards { set; get; }
}
public class CardVm
{
    public int Id { set; get; }
    public string Name { set; get; }
}

现在加入

var decksWithCards = (from dc in db.DeckCards
                join d in db.Decks on dc.DeckID equals d.ID
                join c in db.Cards on dc.CardID equals c.ID
                select new { DeckId = d.ID, DeckName = d.Name,
                             CardId = c.ID, CardName = c.Name })
    .GroupBy(x => x.DeckId, d => d,
        (ky, v) =>
            new DeckVm
            {
                Id = ky,
                Name = v.FirstOrDefault().DeckName,
                Cards = v.Select(h => new CardVm { Id = h.CardId, Name=h.CardName})
            })
    .ToList();

decksWithCards将是List<DeckVm>,您可以将其传递给您的观看。您必须将您的观点强烈输入List<DeckVm>