Question

I am new to linq so please excuse me if I am asking a very basic question:

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

This code is too repetitive and I am sure there is a better way of writing this.

Thanks in advance for looking this up.

Was it helpful?

Solution

Instead of executing query at each line, get commitment entity once:

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

OTHER TIPS

It depends a bit on what you are selecting to, you cannot select from one entity into another in Linq to Entities. If you are using LINQ to SQL and creating the paymentReceiptModel, you can do this.

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

If you are using an already instantiated paymentReceiptModel and just need to assign properties then you are better looking to the solution by lazyberezovsky.

To get around the limitation in Linq to Entities, if that is what you are using, you could do this

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

This essentially, makes the majority of your query Linq to Objects, only the first line is Linq to Entities

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top