【发布时间】:2021-07-29 16:36:40
【问题描述】:
我有以下查询,
var userTree = (from user in users
join location in locations on user.FkHomeLocationId equals location.LocationId
join region in regions on location.RegionId equals region.LocationId
group region by new {
Regionid = region.LocationId,
location.LocationId
}
into grp
select new {
RegionName = regions.FirstOrDefault(s = >s.LocationId == grp.Key.Regionid).LocationName,
Branches = new {
BranchName = locations.FirstOrDefault(b = >b.RegionId == grp.Key.Regionid).LocationName,
Users = users.Where(u = >u.FkHomeLocationId == grp.Key.LocationId).Select(s = >new {
FullName = s.FirstName + " " + s.LastName
}).ToList()
}
}).ToList();
我想将查询结果绑定到模型中。我怎样才能做到这一点。我创建了以下类模型来实现这一点,
public class TreeModel
{
public string RegionName { get; set; }
public Branch Branchs { get; set; }
}
public class Branch
{
public string BranchName { get; set; }
public List<User> Users { get; set; }
}
public class User
{
public string FirstName { get; set; }
}
现在需要将上面的查询数据绑定到这个模型类吗?在不创建 Branch 和 User 类的情况下,有什么最好的方法吗?因为我的应用程序有另一个具有相同名称的类用户和分支,我觉得为查询数据绑定创建像这样的单独类有些内疚?我说的对吗?
更新:我尝试如下,
var userTree = (from user in users
join location in locations on user.FkHomeLocationId equals location.LocationId
join region in regions on location.RegionId equals region.LocationId
group region by new {
Regionid = region.LocationId,
location.LocationId
}
into grp
select new Application.Alerts.Models.AlertUserTreeViewModel() {
RegionName = regions.FirstOrDefault(s = >s.LocationId == grp.Key.Regionid).LocationName,
Branchs = new Application.Alerts.Models.Branch() {
BranchName = locations.FirstOrDefault(b = >b.RegionId == grp.Key.Regionid).LocationName,
Users = new Application.Alerts.Models.User {
FirstName = users.Where(u = >u.FkHomeLocationId == grp.Key.LocationId).FirstOrDefault().FirstName
}
}
}).ToList();
但是我在这一行遇到编译错误,
Users = new Application.Alerts.Models.User {
FirstName = users.Where(u = >u.FkHomeLocationId == grp.Key.LocationId).FirstOrDefault().FirstName
}
作为
无法将类型“Alerts.Models.User”隐式转换为“System.Collections.Generic.List
【问题讨论】:
-
呃..什么?您已经创建了 Branch 和 User 类,那么使用它们吗?
select new TreeModel { RegionName = ... -
@CaiusJard 是的,我试过这样。但问题是
Users = users.Where(u = >u.FkHomeLocationId == grp.Key.LocationId).Select(s = >new { FullName = s.FirstName + " " + s.LastName }).ToList()这部分是怎么做的? -
你有一个 List
因此使用 userTree .FirstOrDefault() 来获取关于类的模型:将构造函数添加到 TreeModel 和 this.Branchs = new Branch()。顺便说一句,使名称和类型相同不是一个好习惯 -
@PowerMouse 如何将查询数据绑定到模型中?
-
1.你有一个 TreeModel 对象的列表。 2. 在 select new {... make: select new TreeModel{ RegionName = ...}
标签: c# entity-framework .net-core entity-framework-core