Why is my DbContext DbSet null?

走远了吗. 提交于 2019-12-04 14:57:39

问题


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.

回答1:


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; }
}



回答2:


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 :)




回答3:


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:

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

    public Repository()
    {
        //your code here...
        People = Set<Person>();
    }
}


来源:https://stackoverflow.com/questions/4270794/why-is-my-dbcontext-dbset-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!