与Linq To SQL和DTO分离关注点 [英] Separating concerns with Linq To SQL and DTO's

查看:57
本文介绍了与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对象会增加工作量,但这似乎是一种更好的方法来紧密绑定Business& amp;数据层,这意味着我可以在没有数据库的情况下测试业务层.

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-designer生成的类.

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< Customer>.而不是IList< Customer>从您的数据访问方法.由于IQueryable< T>继承自IEnumerable< T>应用程序的其余部分应该能够很好地处理它.您还可以在需要时将其转换为列表.

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.

这样做的好处是您可以轻松地动态修改查询,并最大程度地减少从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< Customer> GetCustomers(),您可以通过调用GetCustomers()获得一个客户.Where(c => c.CustomerID == 101).Single();

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天全站免登陆