Reputation: 389
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
Upvotes: 4
Views: 1428
Reputation: 4435
You can use NotMapped
attribute to exclude a field from your model.
using System.ComponentModel.DataAnnotations.Schema;
[NotMapped]
public string SelectedSkills { get; set; }
Upvotes: 6
Reputation: 4456
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();
Upvotes: 1