Wednesday, October 30, 2013

mysql .net Unknown column in 'where clause'

I was having the error :

"Unknown column 'Extent1.Name' in 'where clause'"

The code was:

var companies = (from cp in skydeskDB.Companies
    where cp.OrganizationId == parameters.OrganizationId                                    
    &&  cp.Name.Contains(parameters.Filter)                                                    
      select cp
).OrderBy(cp => cp.Name);


the solution was changing  select cp to select new { cp } :

var companies = (from cp in skydeskDB.Companies

    where cp.OrganizationId == parameters.OrganizationId                                    
    &&  cp.Name.Contains(parameters.Filter)                                                    
      select new { cp } // here
).OrderBy(cp => cp.Name);



Tuesday, October 1, 2013

LINQ - SQL: validate null parameter and apply in where clause

I had the query

 var results =
                        from cs in skydeskDB.Cases
                        where
                        cs.AgentId == AgentId
                        && cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        
                        select cs;

I wanted to avoid the agentid filter when the agentid filter were null, like

                  var results =
                        from cs in skydeskDB.Cases
                        where                        
                        cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        
                        select cs;

and, when  agentid filter were different from null apply the agentid filter, like

var results =
                        from cs in skydeskDB.Cases
                        where
                        cs.AgentId == AgentId
                        && cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        
                        select cs;

The solution is adding the condition (AgentId == null || cs.AgentId == AgentId):

var results =
                        from cs in skydeskDB.Cases
                        where
                        (AgentId == null || cs.AgentId == AgentId)
                        && cs.ClosedAt >= iniDate
                        && cs.ClosedAt < endDate                        

                        select cs;

now I can do both things with one single query:
 - avoid the agentid filter when the agentid filter were null
 - apply agentid filter when the agentid filter were different from null

Resource:
http://stackoverflow.com/questions/9505189/dynamically-generate-linq-queries