0

显然,如果使用以下代码,我会遇到错误。它说:

无法将类型隐式转换System.Linq.IQueryable<AnonymousType>System.Collection.Generic.IEnumerable.

请告诉我如何解决这个问题?

public IEnumerable<Session> GetAllListDetailConsumer(string refId)
{
    ObjectQuery<Session> sessions = db.Sessions;
    ObjectQuery<SessionsList> sessionsLists = db.SessionsList;
    var query =
        from s in sessions
        join sList in sessionsLists on s.ReferralListID equals sList.ReferralListID
        where s.ReferralListID == new Guid(refId)
        select new SessionConsumerList
        {
            ReferralListID = s.ReferralListID,
            SessionServerId = s.SessionServerID,
            ApplicationID = s.ApplicationID,
            // ...
            ConsumerID = sList.ConsumerID,
            ConsumerFirstName = sList.ConsumerFirstName,
            ConsumerFamilyName = sList.ConsumerFamilyName,
            // ...
        };
    return query.ToList();
}
4

2 回答 2

3

您正在选择 using select new,这将创建一个匿名类型,您需要Session在查询中投影到类。

select new Session
{
....

但是请记住,如果您的Session类是表示数据库/数据上下文中的表,那么您不能投影到该类,而是您可能必须创建一个临时类并将选择投影到该类。

编辑 (因为现在问题已被编辑)

现在您正在选择new SessionConsumerList并且正在返回IEnumerable<Session>,您需要修改方法签名以返回IEnumerable<SessionConsumerList>

于 2013-03-05T09:14:24.027 回答
0

为什么不分开创建SessionConsumerList另一种方法呢?使代码更干净。像这样:

public static SessionConsumerList CreateSessionConsumerList(
    Session s,
    SessionsList sList)
{
    return new SessionConsumerList
    {
        ReferralListID = s.ReferralListID,
        SessionServerId = s.SessionServerID,
        ApplicationID = s.ApplicationID,
        // ...
        ConsumerID = sList.ConsumerID,
        ConsumerFirstName = sList.ConsumerFirstName,
        ConsumerFamilyName = sList.ConsumerFamilyName,
        // ...
    };
}

进而:

var query =
    from s in sessions
    join sList in sessionsLists on s.ReferralListID equals sList.ReferralListID
    where s.ReferralListID == new Guid(refId)
    select CreateSessionConsumerList(s, sList);
于 2013-03-06T00:19:20.103 回答