实体框架数据注释
本文关键字:注释 数据 框架 实体 | 更新日期: 2023-09-27 18:10:57
public partial class SystemUser
{
[Display(Name = "User")]
public string Username { get; set; }
[Display(Name = "Pass")]
public string Password { get; set; }
public Nullable<bool> Type { get; set; }
}
当使用此语句从数据库查询时,数据注释工作正常:
context.SystemUsers.ToList();
但是当我在查询中使用'new'关键字时,数据注释将被自动忽略。
context.SystemUsers.Select(u=> new
{
u.Username,
u.Type
});
我想使用第二个查询,我告诉和防止数据注释忽略解决办法是什么?
当我在查询中使用'new'关键字时,数据注释将被自动忽略
这些数据注释仅在SystemUser
类型上表示。但是您的.Select()
子句正在将对象转换为新的匿名类型。它可能具有与SystemUser
相同的直观结构(相同的属性名称/类型等),但作为静态类型语言,它显然是而不是 SystemUser
对象。
为了使用SystemUser
类型,你必须选择该类型:
context.SystemUsers.Select(u => new SystemUser
{
Username = u.Username,
Type = u.Type
});
如果需要数据注释,则如下所示:
context.SystemUsers.Select(u=> new SystemUser
{
u.Username,
u.Type
});
因为你在SystemUser
视图模式中提供了详细信息,如果你只使用new
创建,那么它会创建不包含数据注释的匿名对象