Search code examples
c#linqlinq-to-sqllinq-to-entitieslinq-to-objects

linq query which will return single values and a list in one call


I have this linq call:

PropertyViewModel propertyModel = null;
    propertyModel = (from property in db.LoanProperties
                    join tenant in db.Tenants
                    on property.PropertyId equals tenant.PropertyId
                    where property.LoanApplicationId == newApplication.LoanId
                    select new PropertyViewModel(
                        propertyModel.AddressLine1 = property.AddressLine1,
                        propertyModel.AddressLine2 = property.AddressLine2,
                        propertyModel.TotalRentPerAnnum = property.TotalRentPerAnnum,
                        propertyModel.Tenants = db.Tenants.Where(s => s.PropertyId == property.PropertyId).ToList()
                        ));

My view model:

public class PropertyViewModel
    {
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public decimal? TotalRentPerAnnum { get; set; }
        public List<TenantViewModel> Tenants { get; set; }
    }

I want to cast the tenants under the property from the linq query in my TenantViewModel.

How can I achieve that?

I'm referring to the last line for propertyModel.Tenants.


Solution

  • I hope I understood your question correctly. I guess you were looking for mapping your Tenant database object with your TenantViewModel?

    ropertyViewModel propertyModel = null;
        propertyModel = (from property in db.LoanProperties
                        join tenant in db.Tenants
                        on property.PropertyId equals tenant.PropertyId
                        where property.LoanApplicationId == newApplication.LoanId
                        select new PropertyViewModel(
                            propertyModel.AddressLine1 = property.AddressLine1,
                            propertyModel.AddressLine2 = property.AddressLine2,
                            propertyModel.TotalRentPerAnnum = property.TotalRentPerAnnum,
                            propertyModel.Tenants = db.Tenants.Where(s => s.PropertyId == property.PropertyId).Select(t => new TenantViewModel {//map your properties}).ToList()
                            ));