我的清单应包含哪种类型?

时间:2012-11-06 12:42:00

标签: entity-framework linq-to-entities odata

我有这个查询

List<int> AuctionIds = 
   (from a in _auctionContext.Auctions
    where a.AuctionEventId == auction.AuctionEventId
    select new { a.Id }).ToList();

但是我收到了编译错误

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<int>'

AuctionIds应该是什么类型的?

修改

AuctionIds字段实际上是另一个类(模型类),所以我不能只使用var。我无法相信Jon Skeet没有回答这个问题。

2 个答案:

答案 0 :(得分:0)

您正在向List<int>添加匿名对象。 如果你按照你的方式去做...我会使用var关键字..

var AuctionIds = 
       (from a in _auctionContext.Auctions
        where a.AuctionEventId == auction.AuctionEventId
        select new{Id = a.Id}).ToList();

原因是我不知道匿名对象是什么类型..但编译器应该能够处理它。

修改

呃,关于创建一个AuctionIDModel类?

 public class AuctionIDModel
    {
       int Id{get;set;}
    }

    List<AuctionIDModel> AuctionIds = 
           (from a in _auctionContext.Auctions
            where a.AuctionEventId == auction.AuctionEventId
            select new AuctionIDModel{Id = a.Id}).ToList();

答案 1 :(得分:0)

你可以这样做:

List<int> AuctionIds = _auctionContext.Auctions
    .Where(a => a.AuctionEventId == auction.AuctionEventId)
    .Select(a => a.Id)
    .ToList();