为什么我的DbContext DbSet为空? [英] Why is my DbContext DbSet null?

查看:84
本文介绍了为什么我的DbContext DbSet为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新的Entity Frameworks Code First应用,并且DbSet(人)返回null。

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 :连接字符串

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

现在当我打电话

Repository _repo = new Repository()
_repo.People;

_repo。人将为空

我缺少什么?


  • Microsoft.Data.Entity.Ctp.dll是
    引用了

  • 我尝试了在没有数据库初始化程序的情况下使用

推荐答案

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

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:

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

这篇关于为什么我的DbContext DbSet为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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