Ajith
Ajith

Reputation: 37

Error message when using LINQ with Count(column)

I am trying to write an SQL query into LINQ and I am getting an error when I am fetching the count in the LINQ query. The query in SQL has a left outer join with distinct and count('coulmn'). The error happens at the count keyword inside select new { }

SQL Query:

select MagDesc.MagDescID,  MagDesc.MagTitle, COUNT(*)
from   MagDesc (nolock) 
       left outer join tblDetails (nolock) 
            on MagDesc.MagDescID = tblDetails.MagDescID
where PropertyID is not null
group by MagDesc.MagDescID,  MagDesc.MagTitle

LINQ Query :

var model =
    (
        from mag in _dbContext.MagDesc
        join dt in _dbContext.tblDetails on mag.MagDescID equals dt.MagDescID into dt
        where mag.PropertyID != null
        from subtable in dt.DefaultIfEmpty()
        select new { mag.MagDescID, mag.MagTitle, dt.Count(m=>m.MagDescID) }
    ).Distinct();

This is the Error Message

"Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access."

Please help me with this LINQ query.

Upvotes: 0

Views: 172

Answers (1)

user1023602
user1023602

Reputation:

   dt.Count(m=>m.MagDescID)

That version of .Count takes a function which should return a Boolean.
I'm guessing that MagDescID is not a Boolean...

Perhaps you meant to count the number of IDs instead:

   dt.Select(m => m.MagDescID)
     .Count()

Also you need to give the property a name (as mentioned in another answer):

  select new 
  { 
      mag.MagDescID, 
      mag.MagTitle, 
      magCount = dt.Select(m => m.MagDescID).Count()
  } 

Upvotes: 1

Related Questions