开发者

Is there any difference between manually adding a DbSet or allowing the table to be automatically created?

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; 开发者_JAVA技巧}


        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 DbSet class is to embody the Repository pattern:

Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.

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 DbSet for both types will give you a repository to directly access that entity. This will allow you to query directly for TypeB or directly create/update TypeB instances in the DB, rather than always having to always root your queries in TypeA.

Some of this depends on your associations, though. If you have a constraint on TypeB that requires a TypeA, then you can't create them without a TypeA. However you can still query for them directly.

You can still create or update TypeB instances without the DbSet<TypeB> - simply attach one to the TypeA instance and work against the the DbSet<TypeA>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜