为什么我的 DbContext DbSet 为空?
我创建了一个新的实体框架 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 是 引用
- 我尝试过和 没有数据库初始化程序。
I created a new Entity Frameworks Code First app and the DbSet (People) is returning null.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Repository : DbContext
{
public DbSet<Person> People;
}
web.config: connection string
<connectionStrings>
<add name="Repository"
connectionString="Data Source=|DataDirectory|Repository.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
Now when I call
Repository _repo = new Repository()
_repo.People;
_repo.People
will be null
What I am missing?
- Microsoft.Data.Entity.Ctp.dll is
referenced - I have tried with and
without a database initializer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您在 Repository 类上定义了
DbSet
的字段,而不是属性。添加属性或将其更改为自动属性后,People
将开始为您提供值而不是 null。因此,您需要做的就是将 Repository 类更改为:That's because you define a field of
DbSet<Person>
on Repository class instead of a property. Once you add a property or change it to be a automatic property,People
will start to give you values instead of null. So all you need to do is to change your Repository class to:我刚刚遇到了同样的问题。问题是我确实将这些属性设置为“内部”,而它们必须是“公共”的。以防万一有人仍在寻找:)
I just had the same issue. The problem was that I did set these properties as 'internal' while they must have been 'public'. Just in case someone is still searching :)
我想,如果您像这样使用它们,这些属性也可以是内部/公共的:
I guess, these properties can be internal/public too, if you use them like this: