禁用 Entity Framework Code First 中的列
Disabling Column in Entity Framework Code First
我正在使用 Entity Framework 将数据插入 2 个不同的数据库。有几个列存在于一个数据库中,但不存在于另一个数据库中。它们的数据类型不可为空(int 和 float)。
我不在我的代码中使用这些列(当它们存在时)。意思是我只插入 0 作为它们的数据,但显然我不能发送 null。
有没有一种方法可以让我轻松插入数据,而无需为此创建 2 个不同版本的应用程序?理想情况下,我只想拥有一个模型,其属性类似于在该列中插入 0(如果可用)。
如果您的应用程序仅针对一个数据库运行,那么您可以在 OnModelCreating 中使用一个 IF 语句,该语句使用 Fluent API 来 .Ignore() 缺少的属性。
public class MyDbContextWithMissingColumns: MyDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (myConfig.UseDatabaseWithoutSomeProperties)
{
modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
}
base.OnModelCreating(modelBuilder);
}
}
如果您的应用程序的单个实例连接到两个数据库,那么您必须使用单独的 DbContext 子类型,因为 OnModelCreating 仅针对 AppDomain 中 DbContext 类型的第一个实例运行。
EG:
public class MyDbContextWithMissingColumns: MyDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
base.OnModelCreating(modelBuilder);
}
}
在具有受限字段的数据库的存储库中创建实体:
public class MyClass
{
int MyCommonClassID {get; set;}
string Name {get; set;}
[NotMapped]
string PhoneNumber {get; set;}
}
其中属性[NotMapped]
。使用该字段不会出现在数据库中,但您可以在其他任何地方使用它。你决定在最低级别写入什么,而你的应用程序不关心。
我正在使用 Entity Framework 将数据插入 2 个不同的数据库。有几个列存在于一个数据库中,但不存在于另一个数据库中。它们的数据类型不可为空(int 和 float)。
我不在我的代码中使用这些列(当它们存在时)。意思是我只插入 0 作为它们的数据,但显然我不能发送 null。
有没有一种方法可以让我轻松插入数据,而无需为此创建 2 个不同版本的应用程序?理想情况下,我只想拥有一个模型,其属性类似于在该列中插入 0(如果可用)。
如果您的应用程序仅针对一个数据库运行,那么您可以在 OnModelCreating 中使用一个 IF 语句,该语句使用 Fluent API 来 .Ignore() 缺少的属性。
public class MyDbContextWithMissingColumns: MyDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (myConfig.UseDatabaseWithoutSomeProperties)
{
modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
}
base.OnModelCreating(modelBuilder);
}
}
如果您的应用程序的单个实例连接到两个数据库,那么您必须使用单独的 DbContext 子类型,因为 OnModelCreating 仅针对 AppDomain 中 DbContext 类型的第一个实例运行。
EG:
public class MyDbContextWithMissingColumns: MyDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
base.OnModelCreating(modelBuilder);
}
}
在具有受限字段的数据库的存储库中创建实体:
public class MyClass
{
int MyCommonClassID {get; set;}
string Name {get; set;}
[NotMapped]
string PhoneNumber {get; set;}
}
其中属性[NotMapped]
。使用该字段不会出现在数据库中,但您可以在其他任何地方使用它。你决定在最低级别写入什么,而你的应用程序不关心。