Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my DbContext 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: 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.
like image 855
Jamey McElveen Avatar asked Nov 24 '10 19:11

Jamey McElveen


People also ask

Is DbSet part of DbContext?

Definition. A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.

What is the difference between DbSet and DbContext?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!

What is DbSet in Entity Framework Core?

In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.

How do I get a DbSet?

You can get DbSet from DbContext by Type using the method DbContext. Set(Type entityType) . So if you have the model class name as string you should do some mapping to actual clr type.


2 Answers

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; } } 
like image 189
Morteza Manavi Avatar answered Oct 22 '22 16:10

Morteza Manavi


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

like image 42
Martynas Avatar answered Oct 22 '22 15:10

Martynas