Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create CHECK constraint Use Fluent API? #831

Closed
findmoon opened this issue Sep 23, 2019 · 1 comment
Closed

How to create CHECK constraint Use Fluent API? #831

findmoon opened this issue Sep 23, 2019 · 1 comment

Comments

@findmoon
Copy link

I want to create a check constraint,eg gender

CREATE TABLE `test1` (
  `id` int(11)  NOT NULL AUTO_INCREMENT ,
  `gender` varchar(6) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  CONSTRAINT `constraint_gender` CHECK (`gender` = 'male' or `gender` = 'female')
)

I don't want use migrationBuilder.Sql() create check constraints, so I want to known Weather support Create a CHECK constraint Using Fluent API ? same as HasCheckConstraint...(I doesn't found).

Thank you for your help

@lauxjpn
Copy link
Collaborator

lauxjpn commented Oct 3, 2019

HasCheckConstraint() was added in dotnet/efcore#14673 and then fixed in dotnet/efcore#17052 for EF Core 3.0.

I successfully checked our support for this in the 3.0.0-wip branch with the following test:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.TestUtilities;
using MySql.Data.MySqlClient;
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities;
using Xunit;

namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
    public class ReportedIssuesMySqlTest
        : IClassFixture<ReportedIssuesMySqlTest.ReportedIssuesMySqlFixture>
    {
        [ConditionalFact]
        public virtual void TestIssue831()
        {
            using var context = CreateContext();

            context.Set<test1>()
                .Add(new test1 { gender = "trans" });

            var outerExpection = Assert.Throws<DbUpdateException>(() => context.SaveChanges());
            var innerException = Assert.IsType<MySqlException>(outerExpection.InnerException);
            Assert.Equal(
                innerException.Message,
                "Check constraint 'constraint_gender' is violated.");
        }

        public class test1
        {
            public int id { get; set; }
            public string gender { get; set; }
        }

        public class ReportedIssuesMySqlFixture : SharedStoreFixtureBase<PoolableDbContext>
        {
            protected override void OnModelCreating(
                ModelBuilder modelBuilder,
                DbContext context)
            {
                modelBuilder.Entity<test1>(entity =>
                {
                    entity.HasKey(e => e.id);

                    entity.Property(e => e.gender)
                        .HasMaxLength(6);

                    entity.HasCheckConstraint(
                        "constraint_gender",
                        "`gender` = 'male' or `gender` = 'female'");
                });
            }

            protected override void Seed(PoolableDbContext context)
            {
                context.Set<test1>().AddRange(
                    new test1 { gender = "male" },
                    new test1 { gender = "female" }
                );

                context.SaveChanges();
            }

            protected override ITestStoreFactory TestStoreFactory
                => MySqlTestStoreFactory.Instance;

            protected override string StoreName { get; } = "ReportedIssues";
        }

        public ReportedIssuesMySqlTest(ReportedIssuesMySqlFixture fixture)
            => Fixture = fixture;

        protected ReportedIssuesMySqlFixture Fixture { get; }
        protected DbContext CreateContext() => Fixture.CreateContext();
    }
}

This test throws the following exception (wrapped in a DbUpdateException) as expected:

MySql.Data.MySqlClient.MySqlException: 'Check constraint 'constraint_gender' is violated.'

The test generates the following SQL:

CREATE TABLE `test1` (
    `id` int NOT NULL AUTO_INCREMENT,
    `gender` varchar(6) NULL,
    CONSTRAINT `PK_test1` PRIMARY KEY (`id`),
    CONSTRAINT `constraint_gender` CHECK (`gender` = 'male' or `gender` = 'female')
);

@p0='male' (Size = 6)

INSERT INTO `test1` (`gender`)
VALUES (@p0);
SELECT `id`
FROM `test1`
WHERE ROW_COUNT() = 1 AND `id` = LAST_INSERT_ID();

@p0='female' (Size = 6)

INSERT INTO `test1` (`gender`)
VALUES (@p0);
SELECT `id`
FROM `test1`
WHERE ROW_COUNT() = 1 AND `id` = LAST_INSERT_ID();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants