问题描述
您可以使用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
覆盖OnModelCreating
函数来执行此操作DBContext
:
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 时可用的最新稳定版本。
: 2017 年 9 月
ASP.NET Core(2.0)
如果您使用的是 asp.net core( 撰写本文时为 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; }
}
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; }
}
解决方法
我的理解是,该[NotMapped]
属性在当前处于 CTP 的 EF 5 之前不可用,因此我们无法在生产中使用它。
如何将 EF 4.1 中的属性标记为被忽略?
更新: 我注意到其他一些奇怪的事情。我使该[NotMapped]
属性正常工作,但由于某种原因,EF 4.1 仍会在数据库中创建一个名为
Disposed 的列,即使它public bool Disposed { get; private set; }
被标记为[NotMapped]
.
该类IDisposeable
当然实现了,但我不明白这有什么关系。有什么想法吗?