C# 使用 Entity Framework 4 & Code-First 从数据库中排除字段/属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1707663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exclude a field/property from the database with Entity Framework 4 & Code-First
提问by Yogesh
I will like to know that is there a way to exclude some fields from the database? For eg:
我想知道有没有办法从数据库中排除某些字段?例如:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string FatherName { get; set; }
public bool IsMale { get; set; }
public bool IsMarried { get; set; }
public string AddressAs { get; set; }
}
How can I exclude the AddressAs field from the database?
如何从数据库中排除 AddressAs 字段?
采纳答案by Alex James
In the current version the only way to exclude a property is to explicitly map all the other columns:
在当前版本中,排除属性的唯一方法是显式映射所有其他列:
builder.Entity<Employee>().MapSingleType(e => new {
e.Id,
e.Name,
e.FatherName,
e.IsMale,
e.IsMarried
});
Because AddressAs is not referenced it isn't part of the Entity / Database.
因为 AddressAs 没有被引用,所以它不是实体/数据库的一部分。
The EF team is consideringadding something like this:
EF 团队正在考虑添加如下内容:
builder.Entity<Employee>().Exclude(e => e.AddressAs);
I suggest you tell leave a comment on the EFDesign blog, requesting this feature :)
我建议您在 EFDesign 博客上发表评论,请求此功能:)
Hope this helps
希望这可以帮助
Alex
亚历克斯
回答by kmp
I know this is an old question but in case anyone (like me) comes to it from search...
我知道这是一个老问题,但万一有人(像我一样)从搜索中找到它......
Now it is possible in entity framework 4.3 to do this. You would do it like so:
现在可以在实体框架 4.3 中做到这一点。你会这样做:
builder.Entity<Employee>().Ignore(e => e.AddressAs);
回答by markwilde
for future reference: you can use data annotations MSDN EF - Code First Data Annotations
供将来参考:您可以使用数据注释 MSDN EF - Code First Data Annotations
[NotMapped]
public string AddressAs { get; set; }
回答by Willem Ellis
It's also possible to add the column you want to ignore as a Shadow Propertyin the DbContext:
也可以将要忽略的列添加为DbContext 中的Shadow 属性:
builder.Entity<Employee>().Property<string>("AddressAs");
Then you can query on that column like so:
然后您可以像这样查询该列:
context.Employees.Where(e => EF.Property<string>(e, "AddressAs") == someValue);