加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何首先使用EF核心代码创建连接表

发布时间:2020-12-16 07:29:54 所属栏目:asp.Net 来源:网络整理
导读:我有这三个模型: 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 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在您的数据库中自动创建此表.

第二.在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);
 }

对于使用Eager加载的连接查询,请使用Include();

另外,见下文链接:

Getting more performance out of Entity Framework 6

Entity Framework Loading Related Entities

Configure One-to-Many Relationship

Relationships In EF Core

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读