urig
urig

Reputation: 16831

.NET: How to Define a Unique Constraint using Entity Framework Core 3.1 Migrations' CreateTableBuilder?

I am creating a SQL Server table using Entity Framework Core 3.1 Migrations and utilizing the MigrationBuilder and CreateTableBuilder classes, like so:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "Example",
        columns: table => new
        {
            Id = table.Column<Guid>(nullable: false),
            Foo = table.Column<string>(maxLength: 256, nullable: false),
            Bar = table.Column<string>(maxLength: 256, nullable: false)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Example", x => x.Id);
        });
}

I've been able to define a UNIQUE constraint on a single column like so:

table.UniqueConstraint(
    name: "Unique_Foo", 
    columns: x => x.Foo);

But I need to define a UNIQUE constraint on two columns (ex: Foo and Bar) and I've not been able to express this in the columns argument. (The type of the argument is System.Linq.Expressions.Expression<Func<TColumns,object>>)

How do I define a UNIQUE constraint on two or more columns using the CreateTableBuilder class?

Upvotes: 2

Views: 1336

Answers (1)

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

Try this:

columns: x => new {x.Foo, x.Bar}

Upvotes: 3

Related Questions