简体   繁体   中英

How to make a join table using Entity Framework Core?

I have the following two entities/models:

public class Achievement
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<User> Users { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public ICollection<Achievement> Achievements { get; set; }
}

How to make a join table in Entity Framework Core using the two entities above? Is what I'm doing suffiecient for Entity Framework Core to know the relation and make a join table for it?

I have Many-To-Many relation and I want Entity Framework Core to create a join table like:

public class UserAchievement 
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int AchievementId { get; set; }
}

I did some more research and found that for now there is currently no conventional way to let Entity Framework Core automatically create a join entity for many-to-many relationships, however in the future this might possible .

For now we have to create our own join entity and configure it using Fluent API.

The join entity:

public class UserAchievement 
{
    public int UserId { get; set; }
    public User User { get; set; }

    public int AchievementId { get; set; }
    public Achievement Achievement { get; set; }
}

Other entities:

public class Achievement
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<UserAchievement> UserAchievements { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public ICollection<UserAchievement> UserAchievements { get; set; }
}

and then configure it using Fluent API in DbContext:

public class DataContext : DbContext
{

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserAchievement>().HasKey(ua => new { ua.UserId, ua.AchievementId });
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Achievement> Achievements { get; set; }
    public DbSet<UserAchievement> UserAchievements { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM