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