Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a join table using EF core code first

I have these three models:

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

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?

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

like image 448
tocoolforscool Avatar asked Jan 08 '17 16:01

tocoolforscool


People also ask

How do I use a left join in EF Core?

Left Join. The EF Core converts to above joins into an INNER JOIN. But the other most used join is a SQL left join. To use a left join we use the methodDefaultIfEmpty in the Query Syntax. To implement left join, first we start of with a normal join of two tables. Use the into j1 to push the results of this join into a temp variable j1

What approach do you use to create tables in Entity Framework?

We designed and created tables with Code First approach in .Net Core with Entity Framework Core. You can access codes of project here. Hope to see you in the next post, I wish you healthy days.

How do I set up the EF Core?

Once we have set up the project, the next step is to set up the EF Core. Following are the steps for configuring the EF Core: First, let’s define the model. We will start by creating a folder Models within the root of the application. Let’s add a new class Employee.cs inside: The code above defines the class Employee with some properties.

How to delete table from database using Entity Framework Core code?

Now you can see in the below image that our column is now not accepted a null value. Delete table from database using entity framework core code first approach is so simple you have to remove or comment that table from context file, add migration and then update the database. Now you can see that your table is removed from your database.


2 Answers

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

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 the Model Builder
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     { 
           modelBuilder.Entity<Card>()
                .HasRequired<Card>(_ => _.Card)
                .WithMany(_ => _.Deck);
                
     }

 }

DecksController.cs

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

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

also, see below Links:

Getting more performance out of Entity Framework 6

Entity Framework Loading Related Entities

Configure One-to-Many Relationship

Relationships In EF Core

like image 115
Soheil Alizadeh Avatar answered Oct 29 '22 03:10

Soheil Alizadeh


With your current entity structure, you can write a join between all three data sets and then do a group by on the DeckId and derive the results.

I would create 2 view model classes for this grouped data representation for my view.

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

Now the join

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 will be a List<DeckVm> which you can pass to your view. You have to make your view strongly typed to List<DeckVm>

like image 32
Shyju Avatar answered Oct 29 '22 02:10

Shyju