簡體   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