DbContext - > DbSet - > Where子句丢失(实体框架6) [英] DbContext -> DbSet -> Where clause is missing (Entity Framework 6)

查看:807
本文介绍了DbContext - > DbSet - > Where子句丢失(实体框架6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



基本操作很简单。

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

但是如何使用Where或其他DbSet用户?

  public class MyContext:DbContext 
{
public MyContext()
: base(name = MyContext)
{
//this.Database.Log = Console.Write;
}

public virtual DbSet< User>用户{get;组;
}

用户

  [Table(User)] 
public class User:Base
{
public Guid Id {get;组; }

[StringLength(100)]
public string Username {get;组; }
}

这是不行的问题。

  string username =Test; 
使用(var context = new MyContext())
{
用户u =来自上下文中的用户。用户user.Username == username select user;
}

错误:没有查询的实现源类型为'DbSet'的模式。 哪里没有找到可能没有System.Link的引用或使用指令。



如果我尝试自动完成方法,那么没有。





<强>为什么它不工作? :(



//编辑:
将System.Linq添加到文件顶部会更改上述问题的功能,以便我没有



但是为什么哪里现在错了?

 System.Linq.IQueryable< User>类型不能转换为User显式已经存在显式转换(可能是一个演员丢失)

解决方案

感谢@Grant Winney和@Joe。



使用System.Linq; 将添加到文件的命名空间/顶部,我正在追踪上面的代码来解决问题。 >

使用上面的行,它可以用于列表的第一个项目。

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


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.

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)

解决方案

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();

这篇关于DbContext - &gt; DbSet - &gt; Where子句丢失(实体框架6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆