忽略Entity Framework 4.1 Code First中的类属性

Rah*_*han 291 .net c# entity-framework ef-code-first entity-framework-4.1

我的理解是,在[NotMapped]EF 5当前处于CTP中之前,该属性不可用,因此我们无法在生产中使用它.

如何将EF 4.1中的属性标记为忽略?

更新:我注意到其他一些奇怪的事情.我得到了该[NotMapped]属性,但由于某种原因,即使public bool Disposed { get; private set; }标记为,EF 4.1仍会在数据库中创建一个名为Disposed的列[NotMapped].该IDisposeable课程当然是实现的,但我不知道这应该如何重要.有什么想法吗?

Shy*_*yju 569

您可以使用NotMapped属性数据批注来指示Code-First排除特定属性

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}
Run Code Online (Sandbox Code Playgroud)

[NotMapped]属性包含在System.ComponentModel.DataAnnotations命名空间中.

您也可以在课程中使用Fluent API覆盖OnModelCreating功能执行此操作DBContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

我检查的版本是 EF 4.3,当您使用NuGet时,这是最新的稳定版本.


编辑:2017年9月

Asp.NET核心(2.0)

数据注释

如果您使用的是asp.net核心(在撰写本文时为2.0), [NotMapped]则可以在属性级别使用该属性.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}
Run Code Online (Sandbox Code Playgroud)

流畅的API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于EF的v5>,这些现在存在于System.ComponentModel.DataAnnotations.Schema中 (12认同)
  • 使用[NotMapped]也会告诉其他序列化程序(例如JSON/XML)不映射此属性.如果您希望仅阻止映射到数据库表,但仍有序列化程序访问该属性,则必须使用OnModelCreating方法. (6认同)
  • 谢谢.在他们身后努力看到答案总是好的.在将另一个答案标记为正确之前,我实际上没有注意到你的最后一行.既然你的回答确实存在过,我认为改变你的回答是公平的.我相信@ilmatte不介意. (3认同)

Sha*_*ane 33

从EF 5.0开始,您需要包含System.ComponentModel.DataAnnotations.Schema命名空间.

  • 这仍然是这样吗?我正在使用EF 6.0,至少在我的项目中不再是这种情况.除非我引用了已经在某处引用上述命名空间的命名空间. (2认同)