简体   繁体   中英

EF Core Many to Many relation and HTTP calls

I currently have 2 classes

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

}

and

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

With a many to many relation since a product can be composed of multiple parts and a part can be used in many products.

I read that EF Core still doesn't handle this relation automatically so I will have this joining entity:

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

My question is, when trying to answer the following calls to the api,

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

do I have to write a ProductPartDTO and call that from the Product controller or how exactly do I handle these calls?

I handle this in the DbContext OnModelCreating using a join table.

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

One thing to note, you mention HTTP calls, if using JSON, the JSON serializer will have issues returning this data due to self referencing objects. You'll want to fill DTO (data transfer objects) that do not reference each other when you return your results.

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