DbContext -> DbSet -> Where clause is missing (Entity Framework 6)

后端 未结 2 1605
北海茫月
北海茫月 2021-02-07 15:43

I\'ve read some tutorials with entity framework 6...

The basics are easy.

using (var context = new MyContext())
{
    User u = context.Users.Find(1);
}
<         


        
相关标签:
2条回答
  • 2021-02-07 15:57

    Thanks to @Grant Winney and @Joe.

    Adding using System.Linq; to the namespace/top of the document where i'm tring the code above fixed the problem.

    And using the line above it works for the first item of the list.

    User user = (select user from context.Users where user.Username == username select user).First();
    
    0 讨论(0)
  • 2021-02-07 15:58

    The (second) problem is in what you expect:

    User u = from user in context.Users where user.Username == username select user;
    

    You're expecting a single element. But a Where clause returns a list (IEnumerable) of items. Even if there's only one entity that fits the where clause, it will still return a list (with a single item in it).

    If you want a single item, you need to either take the .First() or the .Single() item of that list.

    Some considerations:

    • Either method I just mentioned can take a clause similar to how the where clause works. This means you can skip the Where and put the clause straight in this method.
    • Single only works if only one element exists (fitting the clause). If two elements occur, an exception will be thrown.
    • First works similar to Single, but it will not throw an exception if multiple items exist (fitting the clause). It will simply return the first element it finds (fitting the clause).
    0 讨论(0)
提交回复
热议问题