My class User is,
public class User
{
public string Username
{
get;
set;
}
public string Password
{
get;
set;
}
public string [] RoleName
{
get;
set;
}
}
Linq to EF,
var innerJoinQuery =
(from u
in db.Users
join ur in db.UserRoles
on u.UserID equals ur.UserID
join r in db.Roles on ur.RoleID equals r.RoleID
select new {
Username=u.Username,
Password=u.Password,
RoleName = r.RoleName, }).ToList();
it result is,
Username = "Abc" Password="123" RoleName = "Admin"
Username = "Test" Password="1234" RoleName = "User"
Username = "Abc" Password="123" RoleName = "Super User"
Manualy i add data in User class object,
List<Models.User> UserList = new List<Models.User>();
UserList.Add(new Models.User { Username ="Abc",Password="123",RoleName = new string[] {"Admin","Supe User"} });
UserList.Add(new Models.User { Username = "Test", Password = "1234", RoleName = new string[] { "User" } });
How to add linq to query data in List Object If you don not understand my question kindly let me know
Thanks
EDITED:
this is not hardcode for these values it can be more than this depend upon query result
Have you tried to instantiate anonymous types instead of Models.User
?
var resultList = (
...
select new {
Username=u.Username,
Password=u.Password,
RoleName = new [r.RoleName] }
)
.ToList();
resultList.Add(new {
Username=u.Username,
Password=u.Password,
RoleName = r.RoleName })
Number and names of fields should be the same in both cases.
UPD
If you want to do it vise versa, than change your innerJoinQuery
select statement to selecting Models.User
, not an anonymous type:
var innerJoinQuery = (
...
select new Models.User {
Username=u.Username,
Password=u.Password,
RoleName = new [] {r.RoleName} // assuming you have string in database
}
)
.ToList();
UserList.AddRange(innerJoinQuery);
If you want to join on local collection inside the query then, AFAIK it is not possible, cause EF will not be able to translate that to SQL.
UPD 2
Have missed that you have array in your Models.User
and The array type 'System.String[]' cannot be initialized in a query result
by your version of EF. so introducing a new Select
after ToList
is your way out:
var innerJoinQuery = (
...
select new {
Username=u.Username,
Password=u.Password,
RoleName = r.RoleName
}
)
.ToList()
.Select(u => new Models.User {
Username=u.Username,
Password=u.Password,
RoleName = new [] {r.RoleName}
});
UserList.AddRange(innerJoinQuery);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.