Have model contain field without adding it to the database?

asp.net asp.net-mvc c# database entity-framework

Question

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
36
8/13/2013 5:28:36 PM

Accepted Answer

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

70
8/13/2013 5:31:37 PM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow