How do I get the EntityFramework to check for 2 parameters?

前端 未结 2 1057
余生分开走
余生分开走 2021-01-27 23:46

I have 3 related objects (non relevant properties omitted for brevity):

public class Product
{
    public int ID { get; set; }
    public virtual ProductPrice Pri         


        
相关标签:
2条回答
  • 2021-01-28 00:28

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-28 00:45

    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:

    • using EF conventions. To achive this, change the name of the ID properties of your entites: for example use ProductId, instead of ID and the conventions will build the model for you
    • using attributes. In this particular case use ForeignKeyAttribute where it applies
    • using the fluent API

    You have some more info on relationships here, with a few simple samples.

    0 讨论(0)
提交回复
热议问题