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

c# entity-framework

Question

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

The basics are easy.

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

But how to use "Where" or something else on the "DbSet" with the 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 thats the problem which doesnt 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 implementation of the query pattern for source type 'DbSet'. 'Where' is not found. Maybe a reference or a using directive for 'System.Link' is missing.

If i try to autocomplete the methods there are none.

VS2013

Why it doesnt works? :(

// Edit: Adding System.Linq to the top of the file changes the functions of the problem above so that i havent a problem anymore.

But why the 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

1
11
10/24/2014 12:24:25 PM

Popular Answer

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();
40
10/24/2014 12:35:33 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow