Linq to Sql DB Object to Domain Object的映射和性能

tbe*_*nin 5 c# sql-server asp.net-mvc delayed-execution linq-to-sql

我在尝试使用LINQ to SQL查询和映射到我的域对象DRY时遇到问题,而不会产生多次往返db的成本.鉴于这个例子:

var query1 = from x in db.DBProducts
            select new MyProduct
            {
                Id = x.ProductId,
                Name = x.ProductName,
                Details = new MyProductDetail
                {
                    Id = x.DBProductDetail.ProductDetailId,
                    Description = x.DBProductDetail.ProductDetailDescription
                }
            }
Run Code Online (Sandbox Code Playgroud)

该查询将对DB进行一次往返.大!但是,我看到的问题是,最终,我还将有一个'GetProductDetails'方法,它还需要做一些SAME"数据对象 - >域对象"映射,与上面非常类似.

为了减轻一些映射,我认为扩展部分数据对象类为我做映射可能是一个很酷的主意,如下所示:

public partial class DBProduct
{
    MyProduct ToDomainObject()
    {
        return new MyProduct
        {
            Id = this.ProductId,
            Name = this.ProductName,
            Details = this.DBProductDetails.ToDomainObject()
        };
    }
}

public partial class DBProductDetail
{
    MyProductDetail ToDomainObject()
    {
        return new MyProductDetail
        {
            Id = this.ProductDetailId,
            Description = this.ProductDetailDescription
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

太好了!现在,我可以简单地重写query1,如下所示:

var query1 = from x in db.DBProducts
            select x.ToDomainObject();
Run Code Online (Sandbox Code Playgroud)

这使代码更干燥,更易读.此外,需要执行相同类型映射的其他查询可以简单地使用ToDomainObject()方法进行映射.它有效,但需要付出代价.在通过Profiler观看时,第一个查询将调用db ONCE,并在必要时连接表.第二个查询没有正确连接,因此多次调用DB.有没有办法完成我正在尝试做的事情:重构LINQ to SQL查询,以便映射到域对象是DRY(没有代码重复)?

Dar*_*rov 1

使用自动映射器。一旦您尝试过,您就不太可能看到如下代码:

new MyProduct
{
    Id = x.ProductId,
    Name = x.ProductName,
    Details = new MyProductDetail
    {
        Id = x.DBProductDetail.ProductDetailId,
        Description = x.DBProductDetail.ProductDetailDescription
    }
}
Run Code Online (Sandbox Code Playgroud)