与分隔条件关注的LINQ to SQL和DTO的 [英] Seperating concerns with Linq To SQL and DTO's

查看:162
本文介绍了与分隔条件关注的LINQ to SQL和DTO的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始了一个新的webforms项目,并决定将业务类从任何DBML引用分开。我的业务层类,而不是访问离散数据层的方法和返回DTO的集合。因此,数据层可以投射DTO的类似如下:

I recently started a new webforms project and decided to separate the business classes from any DBML references. My business layer classes instead access discrete Data layer methods and are returned collections of DTO's. So the data layer might project DTO's like the following:

(from c in dataContext.Customers
where c.Active == true 
select new DTO.Customer
{
   CustomerID = c.CustomerID,
   Name = c.CustomerName,
   ...
}).ToList()

虽然建立DTO对象增加了工作,这种感觉就像一个更好的方法来紧商业与之间的结合;数据层和手段,我没有数据库是目前可以测试业务层。

Although building the DTO objects adds work, this feels like a better approach to a tight binding between Business & Data layers and means I can test the Business layer without a database being present.

我的问题是,这是很好的做法?是否有产生的一种方式DTO的(也许通过SQLMetal),以及什么其他的问题我可能罢工随着项目的进展。

My question is, is this good practice?, Is there a way of generating the DTO's (maybe via SQLMetal), and what other problems might I strike as the project progresses.

推荐答案

我不知道这是否是最好的的做法,但我已经不那么最近写类似的代码,因为我也觉得我可以用我自己的类,而不是我的应用程序中的LINQ的设计器生成的那些改善的关注点分离。

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.

您可能要考虑只返回一个IQueryable<客户>而不是一个IList<客户>从您的数据访问方法。由于IQueryable的< T> T>自IEnumerable<继承;您的应用程序的其它部分应该能够处理它相当不错。你也可以将其转换为当你真的需要一个列表。

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.

这样做的好处是,你可以动态很容易地修改您的查询和minimze返回的数据量从SQL Server。

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

例如:如果你的方法签名是
&IQueryable的LT;客户> GetCustomers的(),你可以通过调用GetCustomers的()得到一个单一的客户在哪里(C => c.CustomerID == 101)。单();

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.

这篇关于与分隔条件关注的LINQ to SQL和DTO的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆