簡體   English   中英

EF核心多對多關系和HTTP調用

[英]EF Core Many to Many relation and HTTP calls

我目前有2節課

public class Product 
{
        public int ProductID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public double Height {get ; set; }
        public double Width {get ; set; }
        public double Depth {get ; set; }
        public ICollection<Part> Parts { get; set; }

}

public class Part
    {
            public int PartID { get; set; }
            public string Name { get; set; }
            public double Price { get; set; }
            public double Height {get ; set; }
            public double Width {get ; set; }
            public double Depth {get ; set; }
            public ICollection<Product> Products { get; set; }
    }

由於產品可以由多個部分組成並且一個部分可以在許多產品中使用,因此具有多對多關系。

我讀到EF Core仍然無法自動處理此關系,因此我將擁有以下加入實體:

public class ProductPart
{
            public int ProductID { get; set; }
            public Product Product { get; set; }
            public int PartID { get; set; }
            public Part Part { get; set; }
}

我的問題是,當嘗試回答以下對api的調用時,

api/Product/{id}/Parts //Parts used in Product with {id}
api/Product/{id}/PartsIn //Products in which Part with {id} is used

我是否必須編寫一個ProductPartDTO並從Product控制器調用它,或者我該如何處理這些調用?

我使用連接表在DbContext OnModelCreating中處理此問題。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>()
                .HasMany(e => e.Parts)
                .WithMany(e => e.Products)
                .Map(m => m.ToTable("ProductParts").MapLeftKey("PartID").MapRightKey("ProductID"));
}

需要注意的一件事是,您提到了HTTP調用,如果使用JSON,則由於自引用對象,JSON序列化程序在返回此數據時會遇到問題。 您需要填充返回結果時不會互相引用的DTO(數據傳輸對象)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM