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

时间:2016-08-17 08:15:52

标签: c# linq linq-to-sql linq-to-entities linq-to-objects

我有这个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的最后一行。

2 个答案:

答案 0 :(得分: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.--- = ----.它就没用了。

答案 1 :(得分: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()
                        ));