linq查询,它将在一次调用中返回单个值和一个列表

问题描述 投票:0回答:2

我有这个linq电话:

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

我的观点模型:

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

我想在我的TenantViewModel中的linq查询中转换属性下的租户。

我怎样才能做到这一点?

我指的是propertyModel.Tenants的最后一行。

c# linq linq-to-sql linq-to-entities linq-to-objects
2个回答
0
投票

我希望我能正确理解你的问题。我猜你是在寻找你的Tenant数据库对象与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()
                        ));

2
投票

这是我的第一个答案!!希望它有所帮助:

对象Tenants和LoanProperties必须具有带外键PropertyId的navigation property。因此,LoanProperties对象必须包含租户列表。

我更喜欢你在最后一行使用的lambda expressions(清洁/清除代码)。尝试这个 :

var propertyModel = db.LoanProperties
        .Where(p => p.LoanApplicationId == newApplication.LoanId)
        .Select(p => new PropertyViewModel(){
                AddressLine1 = p.AddressLine1,
                AddressLine2 = p.AddressLine2,
                TotalRentPerAnnum = p.TotalRentPerAnnum,
                Tenants = p.Tenants.Select(t=> new TenantViewModel(){TenantType = t.TenantType , //other properties...})
                })
                //you don't have to query again, the tenants are already in the LoanProperty objects
                //you just have to transform it on ViewModel with a Select
        .FirstOrDefault();

此外,在PropertyViewModel的构造函数方法中,您不必将propertyModel.--- = ----.放在没用的位置。

© www.soinside.com 2019 - 2024. All rights reserved.