Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Laurent Lequenne 123 posts 248 karma points
    Mar 19, 2018 @ 08:13
    Laurent Lequenne
    0

    Umbraco.Core.Persistence check if field exists

    We have some table with different migrations plan. But we get some issue when we recreate a complete new environment, as the fields in the last model are created. So later migrations fails because fields already exists.

    Is there anyway to define a field with a certain version with the persistence dataannotations ?

    Is there a function to check if a field already exists before running the migration ?

    Thank you.

  • Kevin Jump 2342 posts 14889 karma points MVP 8x c-trib
    Mar 19, 2018 @ 09:38
    Kevin Jump
    1

    Hi

    Migrations are a little different in that the SQL in all the migrations is collated and then ran at the end of the process, so when you are checking for the existence of your column it might not be there because none of your migrations have ran. and when the first one runs it will create the table with all the columns and the subsequent migration then fails.

    if this is whats happening then I would suggest as well as checking for the column you also check for the existence of the table in the later migration. If the table doesn't exist, then it is safe to assume that the first migration hasn't ran yet, but when it does the column will be created as part of the table creation.

    So as an example a later migration might look like :

    var tables = SqlSyntax.GetTablesInSchema(Context.Database).ToArray();
    if (tables.InvariantContains("tableName"))
    {
       var columns = SqlSyntax.GetColumnsInSchema(Context.Database).ToArray();
    
       // check for column
       if (columns.Any(x => x.TableName.InvariantEquals("tableName")
              && x.ColumnName.InvariantEquals("columnName")) == false)
       {
           // create your column here...
           Create.Column("columnName")
               .OnTable("tableName")
               .AsString().Nullable();
       }
    
       // any other columns you might want to add
    }
    
  • Laurent Lequenne 123 posts 248 karma points
    Mar 19, 2018 @ 10:38
    Laurent Lequenne
    0

    That looks great.... Thanks :-)

Please Sign in or register to post replies

Write your reply to:

Draft