Supermode
Supermode

Reputation: 936

Linq in C# using IEnumerable

Appearently, I got an error if using the following code. It said:

Cannot implicity converrt type System.Linq.IQueryable<AnonymousType> to System.Collection.Generic.IEnumerable.

Please advise how I can fix this?

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();
}

Upvotes: 0

Views: 137

Answers (2)

Daniel A.A. Pelsmaeker
Daniel A.A. Pelsmaeker

Reputation: 50376

Why not separate the creation of the SessionConsumerList in another method? Makes the code a lot cleaner. Like this:

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,
        // ...
    };
}

And then:

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);

Upvotes: 0

Habib
Habib

Reputation: 223412

You are selecting using select new, which would create an anonymous type, you need to project to class Session in your query like.

select new Session
{
....

But remember if your Session class is a representing a table in your database/data context, then you can't project to that class, instead you may have to create a temporary class and project the selection to that class.

EDIT (Since the question now has been edited)

Now you are selecting new SessionConsumerList and you are returning IEnumerable<Session>, you need to modify method signature to return IEnumerable<SessionConsumerList>

Upvotes: 3

Related Questions