1

我试图根据我的模型返回一个 IQueryable。

但我需要加入同一个查找表两次。然后将查询变量返回给gridview。

public IQueryable<Benchmark> GetBenchMarks([QueryString("hydrant")] string hydrant,
[QueryString("revdate")] string revdate, [QueryString("street")] string street,
[QueryString("quadrant")] string quadrant, [QueryString("desc")] string desc) {

    IQueryable<Benchmark> query = from p in _db.Benchmarks
    join s in _db.Streets on p.Street1Number equals s.Id
    join s2 in _db.Streets on p.Street2Number equals s2.Id
    select new {
        Street1Name = s.StreetName,
        p.OrderNumber,
        p.HydrantNumber,
        Street2Name = s2.StreetName,
        p.RevisionDate,
        p.Quadrant,
        p.Description,
        p.Street1Number
    };
}

所以在第二个连接到 s2 上有一条红色的曲线。以及以下错误。

Error 5 Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<Benchmarks.Model.Benchmark>'. An explicit conversion exists (are you missing a cast?) C:\Projects\Benchmarks\Benchmarks\Benchmarks_Home.aspx.cs 63 25 Benchmarks

4

2 回答 2

2

Since you end your query with select new {...}, you are creating an anonymous object for each result. Instead, use select p, and each result will be a Benchmark.

However, it looks like returning a Benchmark is not what you want. In this case, you would want to change query to be of type IQueryable or IQueryable<dynamic> (and probably change the return type of the GetBenchMarks function as well, unless it does return IQueryable<Benchmark>!).

A second (potentially better) alternative would be to create a class to represent this anonymous type, and use that.

于 2013-01-22T21:32:56.183 回答
0

您的查询结果是IEnumerable匿名对象,因此无法转换为Benchmark.

如果你想Street1Name从连接关系中设置一些额外的属性( - 显然没有映射到 DB 上),你可以这样做:

 IQueryable<Benchmark> query = from p in _db.Benchmarks
            join s in _db.Streets on p.Street1Number equals s.Id
            join s2 in _db.Streets on p.Street2Number equals s2.Id
        select new { 
                 ....
        };
 var ex = query.ToList();
 var result = new List<Benchmark>();
 foreach(bn in ex){
      result.Add(new Benchmark{ OrderNumber = bn.OrderNumber .... });
 }
// return result.AsQueryable();   
// but now it losts the point to return it as queryable, because the query was already executed so I would simply reurn that list
 return result;

另一种选择是从查询中创建表示对象的新类,并从如下方法返回它:

... select new LoadedBenchmark { Street1Name = s.StreetName ....}
于 2013-01-22T21:43:54.900 回答