Ben
Ben

Reputation: 383

LINQ to SQL with if statement

I have a :

            var query = db.vw_web_GetAccounts; //a sql view
            if (some condition)
            {
                query.Where(...);
            }
            else
            {
                query.Where(...);
            }
            query.Select(a =>  new AccountVM
            {
                Name = a.Name,
                ....
            });

            return query.ToList();

I want to return List<AccountVM>

There is an compilation error:

Error   CS0029  Cannot implicitly convert type 'System.Data.Entity.DbSet<vw_web_GetAccounts>' to 'System.Collections.Generic.List<AccountVM>'

Without the if condition example: It works as expected

var query = db.vw_web_GetAccounts
            .Where(...)
            .Select(a => new AccountVM
            {
                Name = a.Name,
                ....
            });

            return query.ToList();

How do I make it work with if condition?

Upvotes: 0

Views: 58

Answers (2)

Rashid Ali
Rashid Ali

Reputation: 617

Error you are getting have nothing to do with the if condition, but the problem is that method return type is List<AccountVM> but the return value is of type DbSet<vw_web_GetAccounts>

One line solution would be the ternary operator, include condition in the Where clause and rest would be the same as you did in the without if condition version:

var query = db.vw_web_GetAccounts.Where(a => condition ? (...) : (...)).Select(a =>  
            new AccountVM
            {
              Name = a.Name,
              ....
            });

return query.ToList();

Upvotes: 0

Igor
Igor

Reputation: 62213

You need to cast in the 1st statement. Also in the code shown you are missing the assignments.

var query = db.vw_web_GetAccounts as IQueryable<vw_web_GetAccounts>;
if (some condition)
{
    query = query.Where(...);
}
else
{
    query = query.Where(...);
}

return query.Select(a =>  new AccountVM
{
    Name = a.Name,
    ....
}).ToList();

Upvotes: 3

Related Questions