我有这三种模式:
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表是一个静态表(我不知道它是否是正确的术语,但它将填充并保持游戏当前具有的任何卡(它是一个甲板构建网站))。/ p>
答案 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
答案 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>