Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - How to prevent a model property from column creation?

Folks,

I am developing an web application based on ASP .NET MVC 4.

Let's say I define a model such as:

public class MyUser {
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}

The database initializer code will automatically create a table with three columns - UserName, FirstName, and LastName.

However, let's say I don't want LastName to be part of the database table.

Is there any data annotation attribute that I can use to prevent a property from being exposed as a column?

Thank you in advance for your help.

Regards,
Peter

like image 532
Peter Avatar asked Sep 29 '13 19:09

Peter


People also ask

How to ignore class property in Entity Framework?

As other configurations in Entity Framework, there are 2 ways to ignore class property You have to use [NotMapped] Data Attribute on the property which you don’t want to map to the database table column. Below is the updated Customer Model with its DataContext class Some prefer Model classes to be very clean – without any Data Annotations.

How to create an entity data model from a database?

In order to use the Entity Framework, you need to create an Entity Data Model. You can take advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a database automatically.

How to exclude specific entity properties from the database?

Specific properties can be excluded as follows: By convention, when using a relational database, entity properties are mapped to table columns having the same name as the property. If you prefer to configure your columns with different names, you can do so as following code snippet:

What are entity properties in EF Core?

Each entity type in your model has a set of properties, which EF Core will read and write from the database. If you're using a relational database, entity properties map to table columns. By convention, all public properties with a getter and a setter will be included in the model.


1 Answers

use NotMapped attribute. Here is a very good reference about different attribute you can use.

public class MyUser {
    public string UserName { get; set; }
    public string FirstName { get; set; }
    [NotMapped]
    public string LastName { get; set; }

}
like image 74
J.W. Avatar answered Oct 19 '22 04:10

J.W.