简体   繁体   English

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

[英]Entity Framework check if column exists during OnModelCreating

I am maintaining this application (A) that is writing to the table of another application (B).我正在维护这个正在写入另一个应用程序 (B) 表的应用程序 (A)。 The problem is that A writes to many B's and that the models have changed in newer versions of B.问题是 A 写入了许多 B,并且模型在 B 的较新版本中发生了变化。

Example: A has the entity Dog with columns: Name, Age, Sex示例:A 具有实体 Dog,其列:Name、Age、Sex
In most cases of B, this entity matches the table.在 B 的大多数情况下,该实体与表匹配。 But the newest version of B Dog has the columns: Name, Age, Sex, FavoritFood (which does not allow nulls)但是最新版本的 B Dog 有以下列:Name、Age、Sex、FavoritFood(不允许空值)

I can not change the database scheme of B, neither from code nor the sql server.我无法更改 B 的数据库方案,无论是代码还是 sql 服务器。 If I do so, B would just redesign it to its needs.如果我这样做,B 只会根据其需要重新设计它。 I can alter the Dog entity of A but this would need a distinction between newer and older versions of B.我可以更改 A 的 Dog 实体,但这需要区分 B 的新旧版本。

A uses Entity Framework 6.2 as ORM. A 使用实体框架 6.2 作为 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);
    }
}

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.我不仅不能从 OnModelCreating 中访问上下文,而且我发现这种可能性缺乏,因为它非常通用,我想专门检查 FavoritFood 列。

How can I accomplish this?我怎样才能做到这一点?

For anyone else who stumbles upon this: I ended up expanding on @trashr0x comment对于偶然发现此问题的任何其他人:我最终扩展了@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;
    }
}

It seems to work consistently, if someone has some other way, let me know :)它似乎一直有效,如果有人有其他方法,请告诉我:)

You can find it with bellow code你可以用下面的代码找到它

var property = typeof(T).GetProperty("FieldName");
  • T => your class T => 你的班级
  • FieldName => column name you want check it FieldName => 要检查的列名

    if(property == null) //Column not exist else //Column exist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM