4

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

2 Answers 2

6

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

using System.ComponentModel.DataAnnotations.Schema;

[NotMapped]
public string SelectedSkills { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.