实体框架检查在OnModelCreating期间是否存在列 [英] Entity Framework check if column exists during OnModelCreating
问题描述
我正在维护正在写入另一个应用程序(B)的表的该应用程序(A).问题是A写入许多B,并且模型在B的较新版本中已更改.
I am maintaining this application (A) that is writing to the table of another application (B). The problem is that A writes to many B's and that the models have changed in newer versions of B.
示例:A的实体狗"的名称为:姓名,年龄,性别
在大多数情况下,B与表匹配.但是最新版本的B Dog具有以下列:名称,年龄,性别,FavoritFood(不允许为空)
Example: A has the entity Dog with columns: Name, Age, Sex
In most cases of B, this entity matches the table.
But the newest version of B Dog has the columns: Name, Age, Sex, FavoritFood (which does not allow nulls)
我既不能从代码也不能从sql服务器更改B的数据库方案.如果这样做的话,B会根据需要重新设计它.我可以更改A的Dog实体,但这需要在B的新旧版本之间进行区分.
I can not change the database scheme of B, neither from code nor the sql server. If I do so, B would just redesign it to its needs. I can alter the Dog entity of A but this would need a distinction between newer and older versions of B.
A使用Entity Framework 6.2作为ORM.
A uses Entity Framework 6.2 as ORM.
到目前为止,我的想法是:检查列是否存在,如果不忽略该字段.
My idea so far was as follows: Check if column exists, if not ignore the field.
protected override void OnModelCreating(DbModelBuilder builder) {
base.OnModelCreating(builder);
if (!Database.CompatibleWithModel(true)) {
builder.Entity<Dog>().Ignore(_ => _.FavoritFood);
}
}
我不仅不能从OnModelCreating内部访问上下文,而且我发现这种可能性很低,因为它非常通用,我想专门检查一下FavoritFood列.
Not only can't I access the context from within the OnModelCreating I also I find this possibility lacking, since it is very generic and I would like to check specifically for the FavoritFood column.
我该怎么做?
推荐答案
对于其他偶然发现此问题的人:我最后扩展了@ trashr0x评论
For anyone else who stumbles upon this: I ended up expanding on @trashr0x comment
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;
}
}
它似乎可以连续工作,如果有人有其他方法,请告诉我:)
It seems to work consistently, if someone has some other way, let me know :)
这篇关于实体框架检查在OnModelCreating期间是否存在列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!