ghanshyam.mirani
ghanshyam.mirani

Reputation: 3101

Issue Related to SelectMany function in LINQ

I have two tables in Database:

  1. PostCalculationLine
  2. PostCaluclationLineProduct

PostCalculationLineProduct(table2) contains Foriegn key of PostCalucationLineId(table1)

In C# code I have two different Models for these two tables as follows:

public class PostCalculationLine : BaseModel
{
    public long Id{ get; set; }
    public string Position { get; set; }
    public virtual Order Order { get; set; }
    public virtual Task Task { get; set; }
    //some other properties go here
    public virtual IList<PostCalculationLineProduct> PostCalculationLineProducts { get; set; }
}

and

 public class PostCalculationLineProduct : BaseModel
 {
    public long Id {get;set;}
    public string Description { get; set; }
    //some other properties go here
}

Now in Entityframework code, I fetch data from PostCalculationLineProduct as follows:

PostCalculationLineRepository pclr = new PostCalculationLineRepository();
DataSourceResult dsrResult = pclr.Get()
    .SelectMany(p => p.PostCalculationLineProducts)
    .Where(c => c.Product.ProductType.Id == 1 && c.DeletedOn == null)
    .Select(c => new HourGridViewModel()
         {
            Id = c.Id,
            Date = c.From,
            EmployeeName = c.Employee != null ?c.Employee.Name:string.Empty,
            Description= c.Description,
            ProductName = c.Product != null?c.Product.Name :string.Empty,
            From = c.From,
            To = c.Till,
            Quantity = c.Amount,
            LinkedTo = "OrderName",
            Customer ="Customer"
            PostCalculationLineId = ____________
        })
    .ToDataSourceResult(request);

In the above query I want to get PostCalculationLineId(from Table1) marked with underLine. How can I achieve this?

Thanks

Upvotes: 1

Views: 85

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21815

You can use this overload of SelectMany to achieve this:-

  DataSourceResult dsrResult = pclr.Get()
                .SelectMany(p => p.PostCalculationLineProducts,
                (PostCalculationLineProductObj,PostCalculationLineObj) => 
                         new { PostCalculationLineProductObj,PostCalculationLineObj })
                .Where(c => c.PostCalculationLineProductObj.Product.ProductType.Id == 1 
                       && c.PostCalculationLineProductObj.DeletedOn == null)
                .Select(c => new HourGridViewModel()
                {
                    Id = c.PostCalculationLineProductObj.Id,
                    Date = c.PostCalculationLineProductObj.From,
                    //Other Columns here
                    PostCalculationLineId = c.PostCalculationLineObj.Id
                };

This will flatten the PostCalculationLineProducts list and returns the flattened list combined with each PostCalculationLine element.

Upvotes: 3

Related Questions