42

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.

haim770
  • 48,394
  • 7
  • 105
  • 133
Zebedee
  • 475
  • 1
  • 6
  • 11
  • That's why we have **models** and **viewmodels**. The first represent your business objects and they MUST (most of time) be mapped to a database. The later will simply hold any data that your view requires to work properly. – Andre Calil Aug 13 '13 at 17:26
  • Are you using EntityFramework 'Code First'? – haim770 Aug 13 '13 at 17:27
  • @AndreCalil I see but I'd prefer to avoid creating an entire view model seeing as I only have one field value I need a setter and getter for. – Zebedee Aug 13 '13 at 17:29
  • @Zebedee Ok, so review this question, please: http://stackoverflow.com/questions/10385248/ignoring-a-class-property-in-entity-framework-4-1-code-first – Andre Calil Aug 13 '13 at 17:31
  • @AndreCalil it is not true that a model **must** be mapped to a DB. It is very common to have none DB driven Models. – Liam Aug 13 '13 at 21:42
  • @Liam Please, read my comment again. I said *most of times* because, obviously, there may be situations where your model is not tied to your database. Your comment was somewhat useless, to be true. – Andre Calil Aug 14 '13 at 13:35

2 Answers2

88

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

haim770
  • 48,394
  • 7
  • 105
  • 133
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

Community
  • 1
  • 1
Przemysław Kalita
  • 1,977
  • 3
  • 18
  • 28