So i have this LinQ query
var users = from user in dbContext.Users
where user.IsPublic
select user;
The issue is that this user have other properties i don't want returned such as passwordHash or email.
Also selecting into new User{Id=user.Id, First...}
results into an this classic error.. probably because User extends AspNetIdentityUser
The entity or complex type 'MyProject.User' cannot be constructed in a LINQ to Entities query.
I know i could create a new class and select into it but i want the returned to be of type User
Is it possible to remove a property/field from User
at-least set it null when making a query without changing its type?
You can select all the needed properties to an anonymous type, materialize the result and then use the it to build a list of Users. First query uses SQL like syntax, second - chain syntax.
private static void Main(string[] args)
{
List<User> Users = new List<User>()
{
new User {Id = 1, Name = "N1", IsPublic = true},
new User {Id = 2, Name = "N2", IsPublic = true},
new User {Id = 3, Name = "N3"}
};
var users1 = from u in (from user in Users
where user.IsPublic
select new {user.Id, user.Name}).ToList()
select new User {Id = u.Id, Name = u.Name};
var users2 =
Users.Where(x => x.IsPublic)
.Select(user => new {user.Id, user.Name})
.ToList()
.Select(x => new User {Id = x.Id, Name = x.Name});
Console.ReadLine();
}