您可以使用
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/zh-
CN/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; }}流利的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; }}


