Have model contain field without adding it to the database? [closed]

孤者浪人 提交于 2021-02-16 04:09:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!