Entity Framework .Where method chaining

后端 未结 3 424
猫巷女王i
猫巷女王i 2020-12-29 03:38

Is there any difference between these two ways of querying the context?

Firm firm = base.context.Firms
            .Where(f => f.SomeId == someId)
                


        
3条回答
  •  感情败类
    2020-12-29 04:15

    They should both produce the same end result (if I'm not mistaken) but I find the the second is more readable and better shows the original intent.


    Update

    I just verified the above statement using LINQPad. Both queries will, in fact, product the same SQL.

    For example:

    context.SomeTable.Where(c => c.ParentId == null)
                     .Where(c => c.Name.Contains("F"))
                     .Select(c => c.Name);
    

    Produces:

    SELECT [t0].[Name] 
    FROM [SomeTable] AS [t0]
    WHERE ([t0].[Name] LIKE @p0) AND ([t0].[ParentId] IS NULL)
    

    Which is the same SQL that is produced by:

    context.SomeTable.Where(c => c.ParentId == null && c.Name.Contains("F"))
                     .Select(c => c.Name);
    



    You could also compact things a little more (which I find preferable for the same reasons as above):

    var firm = base.context.Firms.FirstOrDefault(f => f.SomeId == someId 
                                                      && f.AnotherId == anotherId);
    

提交回复
热议问题