How to Concatenate Different Types of Objects in LINQ Query using C# method?


(Yay) #1

I have the following C# class:

public class Users
{
    [Key]
    public int ID { get; set; }
    
    [DataMember]
    public string Username { get; set; }
    public string Email { get; set; }
    public AccountType AccountType { get; set; }
}

AccountType is an Enum defined as follows:

public enum AccountType
{
    Free,
    Premium,
    VIP
}

Here is the query function that’s not working:

public string GetUserDetails(int Id)
{
    return from user in SqlDatabaseContext.Users
            orderby user.ID
         select user.Username + ", " + user.Email + ", " + AccountTypeToString(user.AccountType);
}

Is there any alternative to fix this Linq limitation?


(jms) #2

you can’t call AccountTypeToString() in that Linq query.

AccountTypeToString() is a 3rd party method, that cannot be translated to a Transact-SQL equivalent.


(Yassine) #3

The problem as @jms said, Is that you are trying to call this method AccountTypeToString() from Linq.

Linq tries to Translate that method into an Transact-SQL language equivalent, and there isn’t such built in equivalent method in SQL.

Avoid calling that method will solve your issue. here is a simple solution:

1. Create a read-only property in your class:

public class Users
{
    [Key]
    public int ID { get; set; }
    
    [DataMember]
    public string Username { get; set; }
    public string Email { get; set; }
    public AccountType AccountType { get; set; }
    public string AccountTypeString { 
        get
        {
            return AccountTypeToString(this.AccountType);
        }
    }
    
}

2. Implement the AccountTypeToString() method in the same class or somewhere else and call it to do the conversion inside the property.

3. Now change the Linq query to use the new created property like below:

public string GetUserDetails(int Id)
{
    return from user in SqlDatabaseContext.Users
            orderby user.ID
         select user.Username + ", " + user.Email + ", " + user.AccountTypeString;
}

4. That’s it.