排除迁移属性
Exclude properties for migrations
我的模型上有 属性,我不想在迁移后在 表 中生成字段。
是否可以为 Entity Framework 核心迁移排除 属性 ?
我的 DbContext
上是否有模型属性或某些 Fluent API 方法?
您应该能够将 [NotMapped]
指定为 属性 上方的数据注释。
例如如果您想在由 FirstName
和 LastName
组成的模型中包含 FullName
,您可以这样做:
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public string FullName { get;set };
Ignore
方法用于指定下面Contact
class中自动实现的FullName
属性不映射:
public class SampleContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>().Ignore(c => c.FullName);
}
}
public class Contact
{
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
public string Email { get; set; }
}
注意:相当于Ignore方法的Data Annotations是NotMapped
属性。
我的模型上有 属性,我不想在迁移后在 表 中生成字段。
是否可以为 Entity Framework 核心迁移排除 属性 ?
我的 DbContext
上是否有模型属性或某些 Fluent API 方法?
您应该能够将 [NotMapped]
指定为 属性 上方的数据注释。
例如如果您想在由 FirstName
和 LastName
组成的模型中包含 FullName
,您可以这样做:
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public string FullName { get;set };
Ignore
方法用于指定下面Contact
class中自动实现的FullName
属性不映射:
public class SampleContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>().Ignore(c => c.FullName);
}
}
public class Contact
{
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
public string Email { get; set; }
}
注意:相当于Ignore方法的Data Annotations是NotMapped
属性。