编写这个Linq查询的最佳性能(甚至更好的编码实践)是什么



我是linq的新手,所以如果我问一个非常基本的问题,请原谅:

paymentReceiptViewModel.EntityName = payment.CommitmentPayments.First().Commitment.Entity.GetEntityName();
paymentReceiptViewModel.HofItsId = payment.CommitmentPayments.First().Commitment.Entity.ResponsiblePerson.ItsId;
paymentReceiptViewModel.LocalId = payment.CommitmentPayments.First().Commitment.Entity.LocalEntityId;
paymentReceiptViewModel.EntityAddress = payment.CommitmentPayments.First().Commitment.Entity.Address.ToString();

这个代码太重复了,我相信有更好的方法来写这个。

提前感谢您查找此信息。

不在每行执行查询,只获取一次承诺实体:

var commitment = payment.CommitmentPayments.First().Commitment.Entity;
paymentReceiptViewModel.EntityName = commitment.GetEntityName();
paymentReceiptViewModel.HofItsId = commitment.ResponsiblePerson.ItsId;
paymentReceiptViewModel.LocalId = commitment.LocalEntityId;
paymentReceiptViewModel.EntityAddress = commitment.Address.ToString();

这在一定程度上取决于您要选择什么,您不能在Linq to Entities中从一个实体选择到另一个实体。如果您正在使用LINQ to SQL并创建paymentReceiptModel,则可以执行此操作。

var paymentReceiptModel = payment.CommitmentPayments.select(x=>new{
    EntityName = x.Commitment.Entity.GetEntityName(),
    HofItsId = x.Commitment.Entity.ResponsiblePerson.ItsId,
    LocalId = x.Commitments.Entity.LocalEntityId,
    EntityAddress = x.Commitment.Entity.Address
}).FirstOrDefault();

如果你使用的是一个已经实例化的paymentReceiptModel,只需要分配属性,那么你最好看看lazybrezovsky的解决方案。

为了绕过Linq对实体的限制,如果这就是你正在使用的,你可以做这个

var result = payment.CommitmentPayments.select(x=>x);
var paymentReceiptModel= result.select(x=>new 
    {
        EntityName = x.Commitment.Entity.GetEntityName(),
        HofItsId = x.Commitment.Entity.ResponsiblePerson.ItsId,
        LocalId = x.Commitments.Entity.LocalEntityId,
        EntityAddress = x.Commitment.Entity.Address
    }).FirstOrDefault();

从本质上讲,这使得您的大部分查询都是Linq-to-Objects,只有第一行是Linq-toEntities

相关内容

  • 没有找到相关文章

最新更新