I have 3 related objects (non relevant properties omitted for brevity):
public class Product
{
public int ID { get; set; }
public virtual ProductPrice Pri
I was never able to figure out how to fix the models or use the fluent API. I did some lazy loading instead. If anyone has a better solution, please post it.
public class Product
{
public int ID { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string PartNumber { get; set; }
public int CategoryID { get; set; }
public string Description { get; set; }
public int VerticalID = 1;
private ProductPrice _price;
public virtual ProductCategory Category { get; set; }
public virtual ICollection<ProductImage> Images { get; set; }
public virtual ICollection<ProductDocument> Documents { get; set; }
public virtual ICollection<ProductDetail> Details { get; set; }
public virtual ICollection<RelatedProduct> RelatedProducts { get; set; }
// Lazy Loading
public ProductPrice Price
{
get
{
if (_price == null)
{
var db = new ApplicationContext();
_price = db.Prices.FirstOrDefault(p => p.ProductID == ID && p.VerticalID == VerticalID);
}
return _price;
}
}
}
Supposing your DbContext
has a collection of ProductPrice
named ProductPrices
, using LINQ you simply has to make this query:
var price = ctx.ProductPrices.Where(pp =>
pp.ProductId = productId && pp.VerticalId == verticalId).SingleOrDefault();
Where productId
and verticalId
are the available paramters that come from the action paramters, the session, or wherever they are.
The use of single or default warranties that there's only one value on the database, or that there is none, and, on that case, you get null
as a result of the query.
As for your updates I see that your problem is also related to the definition of the relations in the model.
There are 3 ways to achieve it:
ProductId
, instead of ID
and the conventions will build the model for youYou have some more info on relationships here, with a few simple samples.