实体容器中未定义实体集

本文关键字:实体 未定义 | 更新日期: 2024-09-22 18:40:41

在MSDN 上交叉发布

我们为System.Data.Sqlite 使用手动代码优先的实体框架

因此,当创建一个新实体时,我们手动创建表、c#对象,并将DbSet添加到上下文中。

我创建了一个非常简单的对象,在尝试查询上下文时遇到了这个错误。我已经检查了很多次列名和数据类型,但没有发现不匹配的地方。此外,即使字段的名称中有id,也没有定义外键关系。只是一张独立的桌子。

最奇怪的是,我可以向上下文中添加一个新实体,保存更改,并且它将被持久化到数据库中然而,在下一行中,当我尝试检索实体时,会出现The entity set is not defined in the entity container错误。我还注意到,如果我将鼠标悬停在一个实例化的上下文上,所有其他数据库集都将具有EF SQL,如SELECT EXTENT1.myCol as myCol,但department_resources集只显示{System.Data.Entity.DbSet<department_resource>}

对这里的问题有什么想法吗?

以下是我的文件摘录:

DDL

CREATE TABLE department_resources (
dep_res_key VARCHAR PRIMARY KEY, 
department_id INT NOT NULL, 
resource_id INT NOT NULL);

department_resource.cs

[Table("department_resources")]
public class department_resource 
{
    [Key]
    public string dep_res_key { get; set; }
    public int department_id { get; set; }
    public int resource_id { get; set; }
}

MyContext.cs

public class MyContext : DbContext
{
 public DbSet<department_resource> department_resources { get; set; }
}

样品使用

using (MyContext db = new MyContext())
{
    db.department_resources.Add(new department_resource() 
      { dep_res_key = "anID", 
        resource_id = 22, 
        department_id = 23 }); // Works
    db.SaveChanges(); // Also works. Even persists to db
    var foo = from r in db.department_resources 
              select r.resource_id; // Doesn't work. Will error as soon as I try to use foo. Like assigning to a combo box item source. Or even just enumerating the results
    var bar = db.department_resources; // Also doesn't work.
}

实体容器中未定义实体集

问题在于延迟执行。尽管您在using块中分配了foobar,但在MyContext被释放后,直到它们被实际使用,才会对它们进行评估。

您需要强制它们在您的using块中进行评估。例如通过将结果转换为列表。

此外,我注意到您已经在using块中将它们声明为vars。它们需要在外部定义,才能在外部使用(也许你只是在样本中这样做是为了简化?)

List<int> foo;
List<department_resource> bar;
using (MyContext db = new MyContext())
{
    db.department_resources.Add(new department_resource() 
      { dep_res_key = "anID", 
        resource_id = 22, 
        department_id = 23 }); // Works
    db.SaveChanges(); // Also works. Even persists to db
    foo = (from r in db.department_resources 
              select r.resource_id).ToList();
    bar = db.department_resources.ToList();
}

来自MSDN

查询变量本身只存储查询命令。实际查询的执行将延迟,直到您对查询进行迭代foreach语句中的变量。这个概念被称为延迟执行

强制立即执行

对一系列源元素执行聚合功能的查询必须首先迭代这些元素。此类查询的示例有Count、Max、Average和第一这些在没有显式foreach语句的情况下执行,因为查询本身必须使用foreach才能返回结果。另请注意这些类型的查询返回单个值,而不是IEnumerable收集

您还可以通过立即放置foreach循环来强制执行在查询表达式之后。但是,通过调用ToList或ToArray还将所有数据缓存在单个集合对象中。