c# - 如何使用 Entity Framework 在 Linq 中编写列表类型返回值?

标签 c# .net visual-studio-2008 c#-4.0 ado.net-entity-data-model

如何返回 List<personel>来自以下过程的数据类型。如果我按 F5,它会抛出这个错误:

Error 1 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) C:\Documents and Settings\yusufk\Desktop\EFTestSolutions\WebApplicationTest1\WebApplicationTest1\Default.aspx.cs 101 61 WebApplicationTest1

我认为我应该重新排列或重新编码“select new {. . . .”?

protected List<personel> GetPersonalsData2()
{
    List<personel> personeller;
    using (FirmaEntities firmactx = new FirmaEntities())
    {
       personeller = (from p in firmactx.Personals 
                      select new { p.ID, p.Name, p.SurName });
       return personeller.ToList();
    }
 }

 public class personel
 {
    public int ID { get; set; }
    public string Name { get; set; }
    public string SurName { get; set; }
 }

最佳答案

这部分返回一个匿名类型:

personeller = (from p in firmactx.Personals select new { p.ID, p.Name, p.SurName });
return personeller.ToList();

它需要是:

personeller = (from p in firmactx.Personals 
               select new personel { Id = p.ID, 
                                     Name = p.Name, 
                                     SurName = p.SurName }).ToList();

或者如果该集合的类型为 personal你已经可以这样做了:

personeller = (from p in firmactx.Personals select p).ToList();

或者,就是这样:

personeller = firmactx.Personals.ToList();

在您发布的代码中,它试图返回 List<yourAnonymousType> (直接来自 IQueryable,另一个无效转换)而不是 List<personal>并且不能在两者之间转换,你需要处理相同的类型。

关于c# - 如何使用 Entity Framework 在 Linq 中编写列表类型返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2574409/

相关文章:

c# - 返回返回另一个替代方法的结果会在 NSubstitute 中抛出异常

c# - 无法连接到 Sql Server Express 数据库

c++ - 如何从命令行编译 Visual Studio 项目?

c# - 使用系统数据源而不是用户数据源作为 ODBC 连接字符串

c# - 如何将对 System.Data.DataSetExtensions 的引用添加到网站 ascx.cs 文件?

c# - 为什么创建 string.IsNullOrEmpty()?

c# - 为什么在使用 .NET Newtonsoft.Json 组件反序列化一些有效的 json 时,我的 POCO 中的所有集合都是空的

c# - 生成 MyAssembly.XmlSerializers.dll 的目的是什么?

c++ - 即使在设计器中更改高度后,组合框下拉菜单也不起作用

c# - 如何通过使代码变暗而不是 3 个点来恢复 Visual Studio 的旧方式提醒建议?