简体   繁体   中英

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

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

using System.ComponentModel.DataAnnotations.Schema;

[NotMapped]
public string SelectedSkills { get; set; }

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM