问题
In my Asp.NET MVC4 application I want to add a field to my model without adding it to the database.
Sort of a field that only lives in c# instances of the model but not in the database itself.
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.
回答1:
Just decorate your field/property with [NotMapped]
.
For example:
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
[NotMapped]
public string Type { get; set; }
}
See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.notmappedattribute.aspx
回答2:
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
来源:https://stackoverflow.com/questions/18215376/have-model-contain-field-without-adding-it-to-the-database