在“entity framework4.1代码优先”中忽略类属性
我的理解是[NotMapped]属性不可用,直到目前在CTP中的EF 5,所以我们不能在生产中使用它。
我如何标记EF 4.1中的属性被忽略?
更新:我注意到别的奇怪。 我得到了[NotMapped]属性,但由于某种原因,EF 4.1仍然在数据库中创build一个名为Disposed的列,即使public bool Disposed { get; private set; } public bool Disposed { get; private set; } public bool Disposed { get; private set; }用[NotMapped]标记。 当然,这个类实现了IDisposeable ,但我不明白这应该如何。 有什么想法吗?
您可以使用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; } }
[NotMapped]属性包含在System.ComponentModel.DataAnnotations命名空间中。
您也可以使用Fluent API在您的DBContext类中重写OnModelCreating函数:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Customer>().Ignore(t => t.LastName); base.OnModelCreating(modelBuilder); }
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
我检查的版本是EF 4.3 ,这是使用NuGet时可用的最新稳定版本。
编辑 : SEP 2017
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; } }
stream利的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; } }
从EF 5.0起,您需要包含System.ComponentModel.DataAnnotations.Schema命名空间。