Skip to main content
 首页 » 编程设计

c#之Linq 查询在 List 对象中存储一对多集合

2024年05月10日38jillzhang

我有两个具有一对多关系的表(Application 和 Hazard)。

我想将危险列表存储到我的 ViewModel 中的列表对象中。

applicationVm(大大简化为仅显示集合):

 ... 
 public List<Hazard> Hazards { get; set; } 

LINQ 查询(大大简化为仅显示集合):

  IQueryable<ApplicationVm> applVms; 
  applVms = from app in _db.Applications 
    ... 
    join hz in _db.Hazards on app.Id equals hz.ApplicationId into hzr 
      from hzrd in hzr.DefaultIfEmpty() 
    select new ApplicationVm { ..., Hazards = hzrd }; 

Intellisense 显示错误“无法将源类型危害转换为目标类型 List<Hazard> ' 在选择中的 Hazards = hzrd 上。

如何编写此 LINQ 查询。

PS 我不想将 applVms 作为列表返回,因为我是延迟加载。

请您参考如下方法:

我试过了,它有效。

class Program 
    { 
        static void Main(string[] args) 
        { 
            List<Application> application = new List<Application>(); 
            List<Hazard> hazard = new List<Hazard>(); 
            int appID = 1; 
            int hazID = 1; 
            for (int i = 0; i < 10; i++) 
            { 
                application.Add(new Application() { AppID = appID, AppName = string.Format("AppName{0}", i + 1) }); 
                hazard.Add(new Hazard() { HazID = hazID, AppID = appID, HazName = string.Format("HazName{0}", hazID) }); 
                hazID++; 
                hazard.Add(new Hazard() { HazID = hazID, AppID = appID, HazName = string.Format("HazName{0}", hazID) }); 
                hazID++; 
                appID++; 
            } 
 
            IEnumerable<AppHaz> appHaz = from app in application 
                                   select new AppHaz { AppID = app.AppID, Hazards = (from haz in hazard where haz.AppID == app.AppID select haz).ToList() }; 
 
        } 
    } 
 
    class Application 
    { 
        public int AppID { get; set; } 
        public string AppName { get; set; } 
    } 
 
    class Hazard 
    { 
        public int HazID { get; set; } 
        public int AppID { get; set; } 
        public string HazName { get; set; } 
    } 
 
    class AppHaz 
    { 
        public int AppID { get; set; } 
        public List<Hazard> Hazards { get; set; } 
    }