Why is my DbContext DbSet null?

Jamey McElveen picture Jamey McElveen · Nov 24, 2010 · Viewed 24.5k times · Source

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.

Answer

Morteza Manavi picture Morteza Manavi · Nov 24, 2010

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