I have a type called TypeA and somewhere in TypeA there is a property of TypeB (which contains nothing other than an ID and String).
Using Entity Framework, I have created a DbSet of TypeA – public DbSet<TypeA>.
This creates the TypeB column in the database just fine – however, I now need to seed some data. As TypeB does not exist in the original DbContext, I am unable to seed data to it.
I therefore added public DbSet<TypeB> to my original DbContext and it didn’t even detect a change/difference in the Database schema.
So, this got me wondering, and my question is, Is there any difference in creating a separate DbSet over one that is automatically created by a relation?
Sample Code
public class TypeA
{
public int id { get; set; }
public string name { get; set; }
public TypeB foo { get; set; }
}
public class TypeB
{
public int ID { get; set; }
public string name { get; set; }
}
Yes, there is a difference.
In design terms, the point of the
DbSetclass is to embody the Repository pattern:Its purpose is to encapsulate CRUD for a given entity. In order to do this the repository can’t limit itself to just one table. Sometimes it must work with an object tree in the DB.
In your case, having a
DbSetfor both types will give you a repository to directly access that entity. This will allow you to query directly forTypeBor directly create/updateTypeBinstances in the DB, rather than always having to always root your queries inTypeA.Some of this depends on your associations, though. If you have a constraint on
TypeBthat requires aTypeA, then you can’t create them without aTypeA. However you can still query for them directly.You can still create or update
TypeBinstances without theDbSet<TypeB>– simply attach one to theTypeAinstance and work against the theDbSet<TypeA>.