Are Multiple DataContext classes ever appropriate?

后端 未结 5 1950
别跟我提以往
别跟我提以往 2020-12-17 08:19

In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create DataContext classes (which is usually done using the designer in VS 2008). From the

5条回答
  •  一向
    一向 (楼主)
    2020-12-17 08:24

    I have to disagree with the accepted answer. In the question posed, the system has a single large database with strong foreign key relationships between almost every table (also the case where I work). In this scenario, breaking it up into smaller DataContexts (DC's) has two immediate and major drawbacks (both mentioned by the question):

    1. You lose relationships between some tables. You can try to choose your DC boundaries wisely, but you will eventually run into a situation where it would be very convenient to use a relationship from a table in one DC to a table in another, and you won't be able to.
    2. Some tables may appear in multiple DC's. This means that if you want to add table-specific helper methods, business logic, or other code in partial classes, the types won't be compatible across DC's. You can work around this by inheriting each entity class from its own specific base class, which gets messy. Also, schema changes will have to be duplicated across multiple DC's.

    Now those are significant drawbacks. Are there advantages big enough to overcome them? The question mentions performance:

    My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources.

    Actually, it is not true that a large DC takes significantly more time to instantiate or use in a typical unit of work. In fact, after the first instance is created in a running process, subsequent copies of the same DC can be created almost instantaneously.

    The only real advantage from multiple DC's for a single, large database with thorough foreign key relationships is that you can compartmentalize your code a little better. But you can already do this with partial classes.

    Also, the unit of work concept is not really relevant to the original question. Unit of work typically refers to how much a work a single DC instance is doing, not how much work a DC class is capable of doing.

提交回复
热议问题