2013-02-26 74 views
2

嗨我有一个业务逻辑层,它将selectlistitems返回给控制器,然后将传递给视图以填充选择列表。将IEnumerable <SelectListItem>返回给MVC控制器时出错

我有这种方法的工作原理:

public IEnumerable<SelectListItem> GetDevices 
    { 
     get 
     { 
     using (IDeviceData repository = _dataFactory.Create()) 
     { 
      return repository.DeviceTypes.ToList() 
      .Where(dt => dt.ParentId == 10) 
      .Select(dt => 
      new SelectListItem 
      { 
       Text = (dt.Name).Trim(), 
       Value = dt.Id.ToString() 
      }); 
     } 
     } 
    } 

这一点不:

public IEnumerable<SelectListItem> GetGroups(int deviceTypeId) 
    { 
     using (IDeviceData repository = _dataFactory.Create()) 
     { 
      return repository.DeviceTypeConfigurationParameterGroupMaps.ToList() 
      .Where(cm => cm.DeviceTypeId == deviceTypeId) 
      .Join(repository.ConfigurationParameterGroups, cm => cm.ConfigurationParameterGroupId, cg => cg.Id, (cm, cg) => new { cm, cg }) 
      .Select(cg => 
      new SelectListItem 
      { 
       Text = (cg.cg.Name).Trim(), 
       Value = cg.cg.Id.ToString() 
      }); 
     } 
     } 

最明显的区别是两个表之间的连接,我receieve错误是:

Results View = The type '<>f__AnonymousType0<p,d>' exists in both 'System.Web.dll' and 'EntityFramework.dll' 

当试图扩展调试结果时,会接收到此消息。任何意见将EB欢迎因为我不是太熟悉LINQ

+1

从您发布的内容看来,这两个DLL似乎都包含一个类型的定义,该类型与创建为'new {cm,cg}'的匿名类型相匹配。我想,如果你创建了一个助手类(或者使用了一个已经存在的类型)而不是使用匿名类,它可能会工作 – 2013-02-26 10:03:05

+0

谢谢乔安娜,这是问题的一部分。请参阅下面的答案。 – DavidB 2013-02-26 10:41:54

回答

1

想通了:

public IEnumerable<SelectListItem> GetGroupsForDevice(int deviceTypeId) 
    { 
     using (IDeviceData repository = _dataFactory.Create()) 
     { 
      return repository.DeviceTypeConfigurationParameterGroupMaps 
      .Where(cm => cm.DeviceTypeId == deviceTypeId) 
      .Join(repository.ConfigurationParameterGroups, cm => cm.ConfigurationParameterGroupId, cg => cg.Id, (cm, cg) => cg) 
      .ToList() 
      .Select(cg => 
      new SelectListItem 
      { 
       Text = (cg.Name).Trim(), 
       Value = cg.Id.ToString() 
      }).ToList() ; 

     } 
     } 

我需要在连接后添加ToList(),并转换为SelectlistItem后被再次。我也不需要创建新的匿名类型 - 感谢上面的乔安娜。

这是答案,但不是一个很好的解释,如果任何人想填补一点,请随时免费!