Entity Framework check if column exists during OnModelCreating

只愿长相守 提交于 2021-02-08 09:20:06

问题


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.

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)

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 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);
    }
}

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.

How can I accomplish this?


回答1:


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 :)




回答2:


You can find it with bellow code

var property = typeof(T).GetProperty("FieldName");
  • T => your class
  • FieldName => column name you want check it

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



来源:https://stackoverflow.com/questions/60754364/entity-framework-check-if-column-exists-during-onmodelcreating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!