简体   繁体   中英

How to seed new junction table

I am using Code first in Entity framework. There are two tables in my database - Clients and Products. There is some data in it. I have added a new, junction table that has foreign keys to both of them. How should I seed that table? And will Entity framework add new rows when I add new Client or Product, because it seems that it doesn't.:

public class UserPriceList
    {
        public UserPriceList()
        {
            PriceFactor = 1M;
        }

        [Key]
        public int UserPriceListId { get; set; }

        [Index("IX_UserPrice", 1)]
        public int ProductId { get; set; }
        public virtual Product Product { get; set; }

        [Index("IX_UserPrice", 2)]
        public int ClientId { get; set; }
        public virtual Client Client { get; set; }

        public decimal PriceFactor { get; set; }
    }

Your UserPriceList looks a lot like a junction table, but EntityFramework is not viewing it that way because you defined it as an entity with additional properties. A junction table is automatically created behind the scenes as a table with ProductId and ClientId by adding an ICollection to the Client and ICollection to the product. There is no defined model, you would interact with it by Client.Products.Add(someProduct) and it would populate the junction table behind the scenes.

To get your UserPriceList working as a junction table you could try something like this in your OnModelCreating

modelBuilder.Entity<Product>()
    .HasMany(x => x.Clients)
    .WithMany(x => x.Products)
.Map(x =>
{
    x.ToTable("UserPriceList"); // third table is named Cookbooks
    x.MapLeftKey("ProductId");
    x.MapRightKey("ClientId");
});

to explicitly map UserPriceList as the junction table. You may have problems with the non nullable decimal (or maybe not since you're setting a value in the constructor) and with having the UserPriceList defined as an entity.

Your could also just interact with the UserProductList as an entity and explicitly add items to it.

Probably the safest (as in most likely to work) way to go would be to remove the ICollection<Product> from Client and the ICollection<Client> from product add an ICollection<UserPriceList> to both.

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