check constraint entity framework

entity entity-framework

Question

Can I add a check constraint in EF to require the user to provide a valid future date in the "FollowUpDate" field if my CustomerNotes entity contains a boolean "FollowUpRequired" attribute?

1
14
11/5/2012 1:06:15 PM

Accepted Answer

Check constraints are not presently supported by EF.

The check constraint cannot be created in the underlying database by applying an attribute to an entity and then expecting the generated SQL to be suitable.

When using Code First Data Migrations (http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx), one method to get around this is to create a migration and include anSql() inside theUp() created function overrides

e.g.

public override void Up()
{
    // Auto generated code here
    // ...

    // YOUR CUSTOM SQL GOES HERE
    Sql("ALTER TABLE foo ADD CONSTRAINT CK_Some_Check CHECK (SomeDate > '20121110 00:00:00.000'");**
}

For further details, check this query and response as well: Possibility of expressing a check constraint

18
5/23/2017 12:09:20 PM

Popular Answer

Support for EF Core 3.0entity.HasCheckConstraint() now.

Ryan's example, taken:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeTable>(entity =>
        entity.HasCheckConstraint("CK_SomeTable_SomeColumn", "[SomeColumn] >= X");
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow