This is an archived thread from the StopByte developer forum —
browse all archived threads.
StopByte is now a payments & ecommerce toolkit — check out our
free calculators.
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?
2 Likes
jms
(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.
1 Like
Yassine
(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;
}