C# 模型包含字段而不将其添加到数据库中吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18215376/
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
Have model contain field without adding it to the database?
提问by Zebedee
In my Asp.NET MVC4 application I want to add a field to my model without adding it to the database.
在我的 Asp.NET MVC4 应用程序中,我想将一个字段添加到我的模型中而不将它添加到数据库中。
Sort of a field that only lives in c# instances of the model but not in the database itself.
某种仅存在于模型的 c# 实例中而不存在于数据库本身中的字段。
Is there any annotation or other way to exclude the field from the database itself?
是否有任何注释或其他方法可以从数据库本身中排除该字段?
I mean an object I can read and write in runtime which the database has no knowledge of.
我的意思是我可以在运行时读取和写入数据库不知道的对象。
采纳答案by haim770
Just decorate your field/property with [NotMapped]
.
只需用[NotMapped]
.
For example:
例如:
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
[NotMapped]
public string Type { get; set; }
}
回答by Przemys?aw Kalita
That depends what framework you are using to access your data. I assume it's Entity Framework. Well, you can create partial class with the property that you wanty to not be mapped to your database.
这取决于您用于访问数据的框架。我假设它是实体框架。好吧,您可以使用不希望映射到数据库的属性创建分部类。
something like
就像是
public class Class1
{
string Text { get; set; }
int Number { get; set; }
}
public partial class Class1
{
bool IsSomething { get; set; }
}
but that is not advised. More: Entity Framework: add property that don't map to database
但不建议这样做。更多: 实体框架:添加不映射到数据库的属性
Or if you're using Code First: Ignoring a class property in Entity Framework 4.1 Code First
或者,如果您使用的是 Code First: Ignoring a class property in Entity Framework 4.1 Code First