忽略 Entity Framework 4.1 Code First 中的类属性
我的理解是 [NotMapped]
属性直到 EF 5 才可用,它目前在 CTP 中,所以我们不能在生产中使用它.
My understanding is that the [NotMapped]
attribute is not available until EF 5 which is currently in CTP so we cannot use it in production.
如何将 EF 4.1 中的属性标记为忽略?
How can I mark properties in EF 4.1 to be ignored?
更新:我注意到了一些奇怪的事情.我让 [NotMapped]
属性起作用,但由于某种原因,EF 4.1 仍然在数据库中创建一个名为 Disposed 的列,即使 public bool Disposed { get;私人订制;}
用[NotMapped]
标记.该类当然实现了 IDisposeable
,但我不知道这有什么关系.有什么想法吗?
UPDATE: I noticed something else strange. I got the [NotMapped]
attribute to work but for some reason, EF 4.1 still creates a column named Disposed in the database even though the public bool Disposed { get; private set; }
is marked with [NotMapped]
. The class implements IDisposeable
of course but I don't see how that should matter. Any thoughts?
您可以使用 NotMapped
属性数据注释来指示 Code-First 排除特定属性
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
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
命名空间中.
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
您也可以使用 Fluent API
覆盖 DBContext
类中的 OnModelCreating
函数来执行此操作:
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
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时可用的最新稳定版本.
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
编辑:2017 年 9 月
数据标注
如果您使用的是 asp.net core(在撰写本文时为 2.0),则可以在属性级别使用 [NotMapped]
属性.>
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
流畅的 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; }
}