Search code examples
c#asp.net-mvcentity-frameworkentity-framework-6

Entity Framework Custom Annotation


Well, i tried to implement custom annotation for EF 6 just as explained in a tutorial by Milinaudara as it is the first google hit i found. The tutorial is pretty much easy to follow. But, it looked like i will need to add [CaseSensitive] annotation on a column after i ran the first migration - creating table - and the [CaseSensitive] will be actually executed at a second migration as alter table operation. Am I wrong? Because it's what i've experienced so far..

Is it possible for that annotation to be run at table creation? Should i override EF's Generate(CreateTableOperation createTableOperation) method to ensure the [CaseSensitive] annotation actually get applied?


Solution

  • Generate(AlterColumnOperation alterColumnOperation) only got called when the model changed and never get fired on table creation or adding a new column - perhaps this is pretty obvious but the tutorial did not mention it.. at least a background story on each methods will be better.. I end up overriding Generate(AddColumnOperation addColumnOperation) and Generate(CreateTableOperation createTableOperation) so it looked like:

    protected override void Generate(AddColumnOperation addColumnOperation)
    {
        //add the column
        base.Generate(addColumnOperation);
    
        //alter the column
        this.Generate(new AlterColumnOperation(addColumnOperation.Table, addColumnOperation.Column, false));
    }
    
    protected override void Generate(CreateTableOperation createTableOperation)
    {
        //add the column
        base.Generate(createTableOperation);
    
        //alter the column
        foreach(ColumnModel column in createTableOperation.Columns)
        {
            this.Generate(new AlterColumnOperation(createTableOperation.Name, column, false));
        }
    }
    

    Although i know we should never assume every alter operation is safe.. so, passing false when constructing AlterColumnOperation might be a bad idea.