我已经阅读了一些 Entity Framework 6 的教程...
基础很简单。
using (var context = new MyContext())
{
User u = context.Users.Find(1);
}
但是如何在用户的“DbSet”上使用“Where”或其他东西呢?
public class MyContext : DbContext
{
public MyContext()
: base("name=MyContext")
{
//this.Database.Log = Console.Write;
}
public virtual DbSet<User> Users { get; set; }
}
用户
[Table("User")]
public class User : Base
{
public Guid Id { get; set; }
[StringLength(100)]
public string Username { get; set; }
}
这就是行不通的问题。
string username = "Test";
using (var context = new MyContext())
{
User u = from user in context.Users where user.Username == username select user;
}
错误: 没有实现源类型“DbSet”的查询模式。找不到“哪里”。可能缺少“System.Link”的引用或使用指令。
如果我尝试自动完成这些方法,则没有。
为什么它不起作用? :(
//编辑: 将 System.Linq 添加到文件顶部会更改上述问题的功能,这样我就不再有问题了。
但是为什么where
现在是错误的呢?
The type "System.Linq.IQueryable<User>" cant converted into "User" explicit. There already exists an explicit conversion. (Possibly a cast is missing)
最佳答案
感谢@Grant Winney 和@Joe。
将 using System.Linq;
添加到文档的命名空间/顶部,我正在尝试上面的代码解决了这个问题。
并且使用上面的行它适用于列表的第一项。
User user = (select user from context.Users where user.Username == username select user).First();
关于c# - DbContext -> DbSet -> Where 子句丢失( Entity Framework 6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26547603/