Why multiple DbContext classes?

后端 未结 1 1620
無奈伤痛
無奈伤痛 2021-02-14 21:48

When I program using LINQ with a .dbml file, there is only one context. But, when I do an MVC site, it seems like I have separate contexts for each entity (which is the way the

相关标签:
1条回答
  • 2021-02-14 22:42

    There shouldn't be anything stopping you from using one context. The database, and the tooling used to access it, should be completely independent of anything outside of it (business logic, service layer, UI, etc...).

    The number of contexts, or how you use them, shouldn't change based on your client technology.

    What about MVC leads you to believe that you would need more than one context? And what's stopping you from doing so?

    If you think you need to use a context for each entity, because the sample was that way, you don't. Just use one context.

    If it helps, this is what a simple context looks like with more than one entity:

    public partial class abook_dbEntities : DbContext
    {
        public abook_dbEntities()
            : base("name=abook_dbEntities")
        {
        }
    
        public DbSet<Entity> Entities { get; set; }
        public DbSet<Contact> Contacts { get; set; }
    }
    

    If it helps, a typical business flow looks like this:

    UI -> Controller -> Business logic -> Data access -> Database

    Your data contexts would go in your data layer. Your logic would go in your business logic layer.

    0 讨论(0)
提交回复
热议问题