This is a webapi project in .NET 5 and EF Core version 5.0.9. I am testing this API using Swagger. And the database is SQLite.
I have 3 tables Product, StockHeader and StockDetail. StockHeader and StockDetail are in one-to-many relationship.
Product table has these columns->
- Id
- Name
- Rate
StockHeader table has these columns->
- HdrId
- DocumentNo
- Sign
- ICollection of the type StockDetail
StockDetail table has these columns->
- Id
- HdrId(Foreign key)
- ProductId
- Rate
So, my requirement is that when I enter the value of productID in stockDetail,it should look upto the Product table, take the rate of that particular Id and write it in my StockDetails' Rate column.
I have to do this in HttpPost.
The problem is that StockDetail should not have any reference property of Product.
How can I achieve this in EF Core?
CodePudding user response:
Add a simply product property in your stockdetail class and one ienumerable in product class... And add with fluent api a row in your contex, that map productId with your object product...
modelBuilder.Entity<Product>()
.HasMany<StockDetail>(s => s.stockDetaik)
.WithOne(ad => ad.Product)
.HasForeignKey<Product>(ad => ad.ProductId);
CodePudding user response:
Okay so I guess you will have the productId as an input parameter. You just have to make a LINQ query to get the desired product form the Products DbSet.
Try with:
var product = dbContext.Products.FirstOrDefault(x => x.Id == productId);
It is good to check if the input parameter (productId) was a valid Id so you can write this:
if(product == null)
throw new ArgumentException("Invalid ID", nameof(productId));
and after that just assign the Rate so that:
Rate = product.Rate;