简体   繁体   中英

Creating many-to-many relationship code first

I'm trying to create a many-to-many relationship in C# using the code first approach. In the real world, a product can have many categories and a category can have many products. So this is what I've come up with:

Product.cs:

public class Product
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
}

Category.cs:

public class Category
{
    public Category(CategoryEnum @enum)
    {
        Id = (int)@enum;
        Name = @enum.ToString();
    }

    public Category() { }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }


    public static implicit operator Category(CategoryEnum @enum) => new Category(@enum);

    public static implicit operator CategoryEnum(Category category) => (CategoryEnum)category.Id;

}

The Category maps to an Enum which looks like:

public enum CategoryEnum
{
    Electronics = 1,
    Gardening = 2
}

Finally, the DbContext looks like so:

public class ProductDbContext : DbContext
{
    public DbSet<Entities.Product> Products { get; set; }
    public DbSet<Entities.Category> Categories { get; set; }

    public ProductDbContext(DbContextOptions<ProductDbContext> options)
    : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

When running migrations I get this result:

在此处输入图像描述

It's called name the columns like CategoriesId and ProductsId is there a way to change the name of these columns?

Have a go with this:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder
            .Entity<Product>()
            .HasMany(p => p.Categories)
            .WithMany(p => p.Products)
            .UsingEntity<Dictionary<string, object>>("ProductCategory",
              right => right.HasOne<Category>()
                .WithMany()
                .HasForeignKey("CategoryId")
                .HasConstraintName("FK_ProductCategory_CategoryId__Category_Id")
                .OnDelete(DeleteBehavior.Cascade),
              left => left.HasOne<Product>()
                .WithMany()
                .HasForeignKey("ProductId")
                .HasConstraintName("FK_ProductCategory_ProductId__Product_Id")
                .OnDelete(DeleteBehavior.Cascade)
          );
    }

It works:

在此处输入图像描述

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