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

后端 未结 2 509
鱼传尺愫
鱼传尺愫 2021-02-07 15:46

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 16:10

    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).

提交回复
热议问题