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
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.
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.
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:
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.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With