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

前端 未结 2 1059
余生分开走
余生分开走 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: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.

提交回复
热议问题