我有以下三种模型:
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表是静态表(我不知道这是否是正确的用语,但是游戏当前使用的任何纸牌(这是一个套牌建造网站)都将填充它并保持不变。)
第一。您无需为一对多关系创建模型(DeckCard),以便EF自动在数据库中创建此表。
第二。OnModelCreating
在您的DbContext类中添加或覆盖Method例如:
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);
}
对于带有Eager加载的联接查询,请使用Include();
另外,请参见下面的链接:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句