首页 > 解决方案 > .NET:如何使用 Entity Framework Core 3.1 Migrations 的 CreateTableBuilder 定义唯一约束?

问题描述

我正在使用Entity Framework Core 3.1 Migrations创建一个 SQL Server 表并使用MigrationBuilderCreateTableBuilder类,如下所示:

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);
        });
}

我已经能够像这样在单个列上定义一个 UNIQUE 约束:

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

但是我需要在两列(例如:FooBar)上定义一个 UNIQUE 约束,并且我无法在columns参数中表达这一点。(参数的类型是System.Linq.Expressions.Expression<Func<TColumns,object>>

如何使用CreateTableBuilder该类在两个或更多列上定义 UNIQUE 约束?

标签: c#.netentity-framework-coreentity-framework-migrations

解决方案


尝试这个:

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

推荐阅读