LinqToSql declare and instantiate DataContext best practice?

后端 未结 5 1824
-上瘾入骨i
-上瘾入骨i 2020-12-01 14:32

What\'s the best practice in terms of setting up my DataContext for easy access in my extended LinqToSql classes?

For example, I have a \"User\" entity in my dbml a

5条回答
  •  Happy的楠姐
    2020-12-01 15:14

    There are a couple of different ways that you could go about this that would be good practice, I think. First you could use a Repository pattern where you query the Repository for an object, it goes out to the database, retrieves the object -- perhaps detaching it from the data context or keeping the data context around depending on the implementation of the Repository -- and returns it to you. The factory methods for your objects would be on the Repository, not the entities themselves. You'd probably use reflection and generics to minimize the number of methods you have to implement and keep your code DRY.

    The other way, and the way LINQtoSQL was intended to be used natively IMHO, is to create the data context for each set of database operations that you intend to perform. In this the creation of the data context occurs outside the entity as well, usually in the class that is using the entities, not in the data layer at all. You could also add methods to the data context -- make your actual data context abstract and inherit from it -- using reflection again, to perform some of the common retrieval functions so that you don't have to repeat them. You'd probably have to use a database pattern like ActiveRecords where the id columns always have the same name to make this work.

    On the other hand, you could look at using nHibernate or Castle's ActiveRecord instead of replicating either of the above in your own solution.

提交回复
热议问题