entity-framework - 为什么我的 DbContext DbSet 为空?

标签 entity-framework code-first ef-code-first

我创建了一个新的 Entity Framework Code First 应用程序,DbSet (People) 返回 null。

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Repository : DbContext
{
    public DbSet<Person> People;
}

web.config:连接字符串

<connectionStrings>
  <add name="Repository"
       connectionString="Data Source=|DataDirectory|Repository.sdf"
       providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

现在当我打电话

Repository _repo = new Repository()
_repo.People;

_repo.People 将为 null

我缺少什么?

  • Microsoft.Data.Entity.Ctp.dll 是 引用
  • 我尝试过和 没有数据库初始化程序。

最佳答案

那是因为您定义了 DbSet<Person>字段在存储库类而不是属性上。添加属性或将其更改为自动属性后,People将开始为您提供值而不是 null。因此,您需要做的就是将 Repository 类更改为:

public class Repository : DbContext
{
    public DbSet<Person> People { get; set; }
}

关于entity-framework - 为什么我的 DbContext DbSet 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4270794/

相关文章:

c# - Feed RDLC (Local) report 来自 List (Entity FrameWork) 的报告

c# - Code First - 外键引用在分配 Id 时未加载

MySQL + Code First + Lazy Load 问题!

entity-framework - 在 Entity Framework 中添加与同一张表的第二个一对一关系

c# - 为什么 Entity Framework 实体是部分类?

c# - 使 Linq 导航属性对开发人员来说更加明显

c# - Entity Framework 和 ASP.NET Identity

c# - Entity Framework - 有没有一种方法可以在不使用 Include() 的情况下自动预先加载子实体?

c# - 使用 Entity Framework 加载嵌套实体/集合

c# - 自定义类型作为主键