我正在维护正在写入另一个应用程序 (B) 表的应用程序 (A)。 问题是 A 写入了许多 B,并且模型在新版本的 B 中发生了变化。
示例:A 的实体 Dog 的列为:Name、Age、Sex
在 B 的大多数情况下,此实体与表匹配。
但是最新版本的 B Dog 有以下列:Name、Age、Sex、FavoritFood(不允许为空)
我无法更改 B 的数据库方案,无论是从代码还是从 sql server。如果我这样做,B 只会根据需要重新设计它。 我可以更改 A 的 Dog 实体,但这需要区分 B 的新旧版本。
A 使用 Entity Framework 6.2 作为 ORM。
到目前为止我的想法如下:检查列是否存在,如果不存在则忽略该字段。
protected override void OnModelCreating(DbModelBuilder builder) {
base.OnModelCreating(builder);
if (!Database.CompatibleWithModel(true)) {
builder.Entity<Dog>().Ignore(_ => _.FavoritFood);
}
}
我不仅不能从 OnModelCreating 中访问上下文,我还发现这种可能性不足,因为它非常通用,我想专门检查 FavoritFood 列。
我怎样才能做到这一点?
最佳答案
对于偶然发现此问题的其他人: 我最终扩展了@trashr0x 评论
protected override void OnModelCreating(DbModelBuilder builder)
{
base.OnModelCreating(builder);
var exists = CheckIfColumnOnTableExists("Dog", "FavoritFood");
if(!exists)
builder.Entity<Dog>().Ignore(_ => _.FavoritFood);
}
private bool CheckIfColumnOnTableExists(string table, string column) {
using (var context = new DbContext(this.Database.Connection.ConnectionString))
{
var result = context.Database.SqlQuery<int>($@"SELECT Count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '{table}'
AND COLUMN_NAME = '{column}'").Single();
return result == 1;
}
}
它似乎一直有效,如果有人有其他方法,请告诉我:)
关于c# - Entity Framework 检查 OnModelCreating 期间是否存在列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60754364/