【问题标题】:.NET: How to Define a Unique Constraint using Entity Framework Core 3.1 Migrations' CreateTableBuilder?.NET:如何使用 Entity Framework Core 3.1 迁移的 CreateTableBuilder 定义唯一约束?
【发布时间】:2020-08-10 07:40:15
【问题描述】:

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

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

但我需要在两列上定义一个 UNIQUE 约束(例如:FooBar),而我无法在 columns 参数中表达这一点。 (参数类型为System.Linq.Expressions.Expression&lt;Func&lt;TColumns,object&gt;&gt;

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

【问题讨论】:

    标签: c# .net entity-framework-core entity-framework-migrations


    【解决方案1】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 1970-01-01
      • 2021-08-24
      • 2017-05-05
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      相关资源
      最近更新 更多