Reputation: 201
I have this model:
public partial class SystemUser
{
[Display(Name = "User")]
public string Username { get; set; }
[Display(Name = "Pass")]
public string Password { get; set; }
[Display(Name = "Admin")]
public Nullable<bool> Type { get; set; }
}
this function return all record of SystemUser:
public IEnumerable<object> GetAll()
{
var Users = Ctx.SystemUsers.ToList().Select(u => new SystemUser
{
Username = u.Username,
Type = u.Type
});
return Users.ToList();
}
but this query also have password column I dont need this.how can i remove this column from query? i dont want use anonymus type because it remove dataannotation
Upvotes: 0
Views: 457
Reputation: 2795
Try this:
public IEnumerable<object> GetAll()
{
return Ctx.SystemUsers.Select(u => new
{
Username = u.Username,
Type = u.Type
}).ToList();
}
Upvotes: 0
Reputation: 218960
Based on an unnecessarily involved exchange of comments across more than one question, it sounds like what you're really asking is:
I have a type which includes a
Password
field, which I get from the database with Entity Framework. This type includes data annotations which I need to use in an auto-generated UI. I have no control over the UI. How can I provide the UI with a type which includes these data annotations, but doesn't include thePassword
field?
In that case, define another type:
public class SystemUserViewModel
{
[Display(Name = "User")]
public string Username { get; set; }
[Display(Name = "Admin")]
public Nullable<bool> Type { get; set; }
}
And transform to that type:
Ctx.SystemUsers.ToList().Select(u => new SystemUserViewModel
{
Username = u.Username,
Type = u.Type
});
If you use an anonymous object, you don't have a class definition so you don't have any attributes (data annotations). If you use your SystemUser
type then you have a Password
property. To use something which is neither of these things, you have to define a type.
Upvotes: 0
Reputation: 19200
You can use a DTO and AutoMapper Queryable Extensions to support this scenario:-
public class SystemUserDto
{
[Display(Name = "User")]
public string Username { get; set; }
[Display(Name = "Admin")]
public Nullable<bool> Type { get; set; }
}
...
Mapper.CreateMap<SystemUser, SystemUserDto>();
...
public IEnumerable<SystemUserDto> GetAll()
{
var Users = Ctx.SystemUsers.Project().To<SystemUserDto>();
}
Upvotes: 0
Reputation: 39966
You should return Anonymous Types
in GetAll()
method. Change GetAll
like this:
public IEnumerable<object> GetAll()
{
var Users = Ctx.SystemUsers.ToList().Select(u => new
{
User = u.Username,
Admin = u.Type
});
return Users.ToList();
}
Upvotes: 1
Reputation: 9508
No way of doing this without raw sql. You always fetch entire table row with Entity Framework.
Upvotes: 0