1

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

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

提前感谢您查找此内容。

4

2 回答 2

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();
于 2013-07-22T06:57:15.710 回答
0

这有点取决于您选择的内容,您无法在 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

于 2013-07-22T07:13:25.543 回答