Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework check if column exists during OnModelCreating

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?

like image 921
Pio Avatar asked Sep 18 '25 05:09

Pio


1 Answers

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

like image 184
Pio Avatar answered Sep 19 '25 18:09

Pio