Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC5 - How to enforce Entity Framework to ignore properties in model?

I am using Entity Framework with a code-first approach. I wanted to have a property / attribute in my model but I don't want it to be a column in my database when I perform a migration?

An example model:

public class Class
{
    public int Id { get; set; }

    [Required]
    public int SkillId { get; set; }
    public Skill Skill { get; set; }

    public string SelectedSkills { get; set; }

    public int Repeat { get; set; }
}

In the above example, how can I have the SelectedSkills and Repeat properties without having them as columns in the database?

Can I achieve this using the private keyword?

Thank you

like image 398
Mr Nobody Avatar asked Oct 24 '25 04:10

Mr Nobody


2 Answers

You can use NotMapped attribute to exclude a field from your model.

using System.ComponentModel.DataAnnotations.Schema;

[NotMapped]
public string SelectedSkills { get; set; }
like image 163
Raj Avatar answered Oct 25 '25 16:10

Raj


It seems that you are mixing the view model with the entity model which is wrong.

Your view model should be a separte class which has all the needed properties in the HTML View.

Your entity model should only have the data that need persistence.

So, you have to create another class. ex:

public class Class
{
    public int Id { get; set; }

    [Required]
    public int SkillId { get; set; }
    public Skill Skill { get; set; }
}

public class ClassModel
{
    public int Id { get; set; }

    [Required]
    public int SkillId { get; set; }

    public string SelectedSkills { get; set; }

    public int Repeat { get; set; }
} 

If for any reason you must ignore a specific property then you can add annotation [Ignore] or in your data context's OnModelCreating method use the modelBuilder.Entity<Class>().Property(a=>a.Repeat).Ignore();

like image 31
Haitham Shaddad Avatar answered Oct 25 '25 16:10

Haitham Shaddad