[英]ASP.NET MVC5 - How to enforce Entity Framework to ignore properties in model?
我正在以代碼優先的方式使用Entity Framework。 我想在模型中有一個屬性/屬性,但是當我執行遷移時,我不希望它成為數據庫中的一列嗎?
示例模型:
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; }
}
在上面的示例中,如何在不具有SelectedSkills
和Repeat
屬性的情況下將其作為數據庫中的列?
我可以使用private
關鍵字實現嗎?
謝謝
您可以使用NotMapped
屬性從模型中排除字段。
using System.ComponentModel.DataAnnotations.Schema;
[NotMapped]
public string SelectedSkills { get; set; }
看來您正在將視圖模型與實體模型混合在一起,這是錯誤的。
您的視圖模型應該是一個separte類,它在HTML視圖中具有所有必需的屬性。
您的實體模型應該只包含需要持久性的數據。
因此,您必須創建另一個類。 例如:
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; }
}
如果出於任何原因必須忽略特定屬性,則可以添加注釋[忽略],或者在數據上下文的OnModelCreating
方法中使用modelBuilder.Entity<Class>().Property(a=>a.Repeat).Ignore();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.