实体框架在 OnModelCreating 期间检查列是否存在

Pio*_*Pio 4 .net c# entity-framework

我正在维护这个应用程序(A),它正在写入另一个应用程序(B)的表。问题是 A 写入了许多 B,并且模型在 B 的新版本中发生了变化。

示例:A 具有实体 Dog,其列为:姓名、年龄、性别
在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不仅无法从 OnModelCreating 中访问上下文,而且我还发现缺乏这种可能性,因为它非常通用,我想专门检查 FavoritFood 列。

我怎样才能做到这一点?

Pio*_*Pio 9

对于其他偶然发现这一点的人:我最终扩展了 @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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它似乎始终有效,如果有人有其他方法,请告诉我:)