繁体   English   中英

如何播种新的联结表

[英]How to seed new junction table

我首先在实体框架中使用Code。 我的数据库中有两个表-客户和产品。 里面有一些数据。 我添加了一个新的联结表,它们都具有外键。 我应该如何播种那个桌子? 当我添加新的Client或Product时,Entity Framework会添加新行,因为似乎没有。

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

您的UserPriceList看起来很像一个联结表,但是EntityFramework并不以这种方式查看它,因为您已将其定义为具有其他属性的实体。 通过将ICollection添加到Client并将ICollection添加到产品,将在幕后自动创建一个带有ProductId和ClientId的表,作为具有ProductId和ClientId的表。 没有定义的模型,您可以通过Client.Products.Add(someProduct)与它进行交互,并且它将在幕后填充联结表。

为了使您的UserPriceList可以作为联结表,您可以在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");
});

显式地将UserPriceList映射为联结表。 您可能会遇到以下问题:不可为空的十进制数(或者可能不是因为您在构造函数中设置了值),并且将UserPriceList定义为实体。

您还可以仅作为一个实体与UserProductList进行交互,并向其中明确添加项目。

可能最安全(最可能可行)的方法是从客户端删除ICollection <Product>,从产品删除ICollection <Client>,同时向两者添加ICollection <UserPriceList>。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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