Entity Framework Pitfalls: Non Public Entity Sets Setter

Updated

When defining your entity sets in a Code First context (DbContext), you declare your entity sets as properties of the DbSet<T> type. Weird as it may seem, these properties need to be declared with both a public getter and setter. It really doesn’t make much sense, because you wouldn’t want to set these properties from outside the context, but that’s how it is. So, this won’t work:

   1: public DbSet<Product> Products { get; protected set; }

While this does:

   1: public DbSet<Product> Products { get; set; }

You can have non-public setters provided you initialize them explicitly in the constructor by calling Set<T>, because EF won't do it for you. Don’t ask me why! Winking smile

Update: this no longer happens in Entity Framework Core.

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website