Separating concerns with Linq To SQL and DTO's

故事扮演 提交于 2019-11-30 12:46:55

I don't know if it's best practice but I have written similar code in the not so recent past because I too felt that I could improve the separation of concerns by using my own classes instead of the LINQ-designer-generated ones within my application.

You may want to consider just returning an IQueryable<Customer> instead of an IList<Customer> from your data-access method. Since IQueryable<T> inherits from IEnumerable<T> the rest of your app should be able to deal with it quite well. You can also convert it to a List when you really need to.

The advantage of this is that you can dynamically modify your query quite easily and minimze the amount of data returned from SQL Server.

E.g. if your method signature is IQueryable<Customer> GetCustomers() you could get a single customer by calling GetCustomers().Where(c => c.CustomerID == 101).Single();

In this example only one record would be returned from the database whereas I imagine currently your code would return either all customers or you'd be required to write separate methods (and thus very repetitive code) to cater for all the different things you may want to filter by.

In my opinion in most cases DTO objects are not needed when dealing with LINQ. Generated LINQ classes can be easily tested. LINQ gives you ability to query your data from different sources using identical queries. It gives you ability to test your queries against lists of objects instead of real db.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!