Have model contain field without adding it to the database?

27,684

Solution 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

Solution 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

Share:
27,684
Zebedee
Author by

Zebedee

Updated on July 09, 2022

Comments

  • Zebedee
    Zebedee almost 2 years

    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.