是否模型包含字段而不将其添加到数据库?

时间:2022-04-14 07:10:42

In my Asp.NET MVC4 application I want to add a field to my model without adding it to the database.

在我的Asp。NET MVC4应用程序我想在模型中添加一个字段,而不需要将它添加到数据库中。

Sort of a field that only lives in c# instances of the model but not in the database itself.

这类字段只存在于模型的c#实例中,而不存在于数据库本身。

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.

我的意思是,我可以在运行时读取和写入的对象,而数据库对此一无所知。

2 个解决方案

#1


41  

Just decorate your field/property with [NotMapped].

用[notmapping]来装饰你的字段/属性。

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

参见http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.notmappedattribute.aspx

#2


1  

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

或者,如果您首先使用代码:忽略实体框架4.1中的类属性

#1


41  

Just decorate your field/property with [NotMapped].

用[notmapping]来装饰你的字段/属性。

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

参见http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.notmappedattribute.aspx

#2


1  

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

或者,如果您首先使用代码:忽略实体框架4.1中的类属性