【问题标题】:What is the performance optimum (or even better coding practise) for writing this Linq query编写此 Linq 查询的最佳性能(甚至更好的编码实践)是什么
【发布时间】:2013-07-22 06:55:08
【问题描述】:

我是 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();

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

提前感谢您查找此内容。

【问题讨论】:

  • 您是否在使用 ORM(即使用实体框架、Linq to SQL 等)?

标签: linq asp.net-mvc-4 controller viewmodel asp.net-mvc-viewmodel


【解决方案1】:

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

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();

【讨论】:

  • 感谢您的快速回复。
【解决方案2】:

这在一定程度上取决于您选择的内容,您无法在 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 并且只需要分配属性,那么您最好寻找lazyberezovsky 的解决方案。

要绕过 Linq to Entities 中的限制,如果您正在使用它,您可以这样做

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 to Entities

【讨论】:

  • 谢谢@James,我已经实例化了 paymentReceiptModel,我正在尝试分配一些属性。
猜你喜欢
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2020-10-19
  • 1970-01-01
  • 2020-07-09
  • 2013-06-18
相关资源
最近更新 更多