Search code examples
jsonentity-frameworkentity-framework-coresql-server-2016code-first

How can I add a check constraint for JSON in Entity Framework?


Adding a JSON CHECK CONSTRAINTfor a table field with

ALTER TABLE [dbo].[Data]  
   ADD CONSTRAINT [JsonData must be formatted as JSON] 
   CHECK  (IsJson([JsonData]) > 0)

works fine, but I want to make it work for Code First.

I have tried the Reverse Engineering Code First, but it does not help me with this problem. Executing a Sql Command with the same code (Seed() method) works very well, but this is not one of the solutions I would like to use:

protected override void Seed(MyContext context)
{
    context
    .Database
    .ExecuteSqlCommand(
        "ALTER TABLE [dbo].[Data]  
            ADD CONSTRAINT [JsonData must be formatted as JSON] 
            CHECK  (IsJson([JsonData]) > 0)");
}

Is there any other way I can add a JSON Check Constraint from Code First?


Solution

  • I think that EF don't support any kind of CHECK constraints. The only thing that you can use is migration. See example in: Is it possible to add CHECK constraint with fluent API in EF7?