LINQ ExecuteQuery
11,491
Sure just write.
var q = "SELECT userID as UserIdentity, levID as LevelIdentity FROM UserLevel";
var res = context.ExecuteQuery<UserLevelDTO>(q);
But why not use Linq instead? You could write:
var res = from u in context.UserLevel
select new UserLevelDTO()
{
UserIdentity = u.userID,
LevelIdentity = u.levID
};
You would need to create your own DTO class.
public class UserLevelDTO
{
public int UserIdentity { get; set; }
public int LevelIdentity { get; set; }
}
Author by
mrd
Updated on June 04, 2022Comments
-
mrd almost 2 years
I want to use ExecuteQuery() to get IEnumerable of type Entities.UserLevel. Following code works well.
using (CDataContext context = data.GetDataContext()) { string q = "SELECT *FROM UserLevel"; IEnumerable<Entities.UserLevel> res = context.ExecuteQuery<Entities.UserLevel>(q); } public class UserLevel { public int userID { get; set; } public int levID { get; set; } }
But the problem is that I must use property names in UserLevel class same as in database, otherwise I do not get values. I wonder is there any way to get values irrespective of class/property name? For example, I want to use following UserLevel class instead of above:
public class UserLevel { public int UserIdentity { get; set; } public int LevelIdentity { get; set; } }
-
mrd over 11 yearsThanks. My application requires complex search options where I do not know on what fields user want to search on, so I chose to use ExecuteQuery. Do you know some better ways of doing it?
-
Magnus over 11 years@mrd So you need to build a dynamic sql query? There is a dynamic library for linq also.