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.

6
  • 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. Aug 13, 2013 at 17:26
  • Are you using EntityFramework 'Code First'?
    – haim770
    Aug 13, 2013 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, 2013 at 17:29
  • @Zebedee Ok, so review this question, please: stackoverflow.com/questions/10385248/… Aug 13, 2013 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, 2013 at 21:42

2 Answers 2

87

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.