一次调用将 return 单个值和一个列表的 linq 查询

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

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

希望我正确理解了你的问题。我猜您是在寻找将 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()
                        ));

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

Tenants 和 LoanProperties 对象必须具有 navigation property 外键 PropertyId。因此,一个 LoanProperties 对象必须有一个租户列表。

我更喜欢你在最后一行(clean/clear 代码)中使用的 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.--- = ----.也没用