DbContext & # 8594; DbSet & # 8594; Where the offer is missing (Entity Framework 6)

I read several tutorials with framework 6 entity ...

The basics are simple.

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

But how to use โ€œWhereโ€ or something else in โ€œDbSetโ€ with users?

 public class MyContext : DbContext { public MyContext() : base("name=MyContext") { //this.Database.Log = Console.Write; } public virtual DbSet<User> Users { get; set; } } 

Users

 [Table("User")] public class User : Base { public Guid Id { get; set; } [StringLength(100)] public string Username { get; set; } } 

And this is a problem that does not work.

 string username = "Test"; using (var context = new MyContext()) { User u = from user in context.Users where user.Username == username select user; } 

Error: There was no request template implementation for the source type DbSet. "Where" not found. Maybe the link or use of the directive for "System.Link" is missing.

If I try to autocomplete methods, they are not.

VS2013

Why does this not work ?: (

// Edit: Adding System.Linq to the beginning of the file changes the function of the problem above, so I no longer have the problem.

But why where is wrong now?

 The type "System.Linq.IQueryable<User>" cant converted into "User" explicit. There already exists an explicit conversion. (Possibly a cast is missing) 

above doesnt work, bottom works

+6
source share
2 answers

Thanks to @Grant Winney and @Joe.

Addition using System.Linq; to the namespace / vertex of the document, where I execute the code above, fixed the problem.

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

 User user = (select user from context.Users where user.Username == username select user).First(); 
+22
source

The problem (second) is what you expect:

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

You are expecting one item. But the Where clause returns a list of (IEnumerable) elements. Even if there is only one entity that matches the where clause, it will still return a list (with one element in it).

If you need one item, you need to either take the .First() or .Single() element of this list.

Some considerations:

  • Any method I just mentioned can accept a sentence similar to how the where clause works. This means that you can skip Where and place the sentence directly in this method.
  • Single only works if there is only one element (setting sentence). If two elements occur, an exception will be thrown.
  • First works like Single , but will not throw an exception if there are multiple elements (customizing the sentence). It will simply return the first element that it finds (setting the sentence).
+1
source

Source: https://habr.com/ru/post/977175/


All Articles