简体   繁体   中英

Table only with foreign key in entity framework 6 (Fluent Api)

How to map foreign keys from two different table to one table in fluent Api? My two model is like

public class Customer
{
    [Key]
    public string Userid { get; set; }

    public string PassWord { get; set; }

    public bool premium { get; set; }
}


public class Roles
{
    [Key]
    public string Name { get; set; }

    public string Description { get; set; }
}

And 3rd table which has primary key of above table as foreign key?

public class CustomerRoles
{
   public string RoleName { get; set; }
   public string UserId { get; set; }
}

How to map in Fluent Api?

public class Customer
{
    [Key]
    public string Userid { get; set; }
    public string PassWord { get; set; }
    public bool premium { get; set; }
    public ICollection<CustomerRole> CustomerRoles { get; set; }
}
public class Role
{
    [Key]
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<CustomerRole> CustomerRoles { get; set; }
}
public class CustomerRole
{
    public string RoleName { get; set; }
    public string UserId { get; set; }
    public Role Role { get; set; }
    public Customer Customer { get; set; }
}
public class AppContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Role> Roles { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Customer>().HasMany(c => c.CustomerRoles).WithRequired(cr => cr.Customer);
        modelBuilder.Entity<Role>().HasMany(r => r.CustomerRoles).WithRequired(cr => cr.Role);
        modelBuilder.Entity<CustomerRole>().HasKey(cr => new { cr.RoleName, cr.UserId });
    }
}

PS: Class name should not be plural, it can confuse with array property.

update how to use it

static void Main(string[] args)
{
    using (var ctx = new AppContext())
    {
        Customer customer = new Customer { Userid = "A" };
        ctx.Customers.Add(customer);

        Role role1 = new Role { Name = "Role1" };
        ctx.Roles.Add(role1);
        Role role2 = new Role { Name = "Role2" };
        ctx.Roles.Add(role2);

        customer.CustomerRoles = new[]
        {
            new CustomerRole { Customer = customer, Role = role1 },
            new CustomerRole { Customer = customer, Role = role2 },
        };

        ctx.SaveChanges();
    }
}

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