I\'ve read some tutorials with entity framework 6...
The basics are easy.
using (var context = new MyContext())
{
User u = context.Users.Find(1);
}
<
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:
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).