简体   繁体   English

ASP.NET MVC5-如何强制实体框架忽略模型中的属性?

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

I am using Entity Framework with a code-first approach. 我正在以代码优先的方式使用Entity Framework。 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? 在上面的示例中,如何在不具有SelectedSkillsRepeat属性的情况下将其作为数据库中的列?

Can I achieve this using the private keyword? 我可以使用private关键字实现吗?

Thank you 谢谢

You can use NotMapped attribute to exclude a field from your model. 您可以使用NotMapped属性从模型中排除字段。

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. 您的视图模型应该是一个separte类,它在HTML视图中具有所有必需的属性。

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(); 如果出于任何原因必须忽略特定属性,则可以添加注释[忽略],或者在数据上下文的OnModelCreating方法中使用modelBuilder.Entity<Class>().Property(a=>a.Repeat).Ignore();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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