简体   繁体   English

.NET:如何使用 Entity Framework Core 3.1 Migrations 的 CreateTableBuilder 定义唯一约束?

[英].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:我正在使用Entity Framework Core 3.1 迁移并利用MigrationBuilderCreateTableBuilder类创建 SQL 服务器表,如下所示:

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:我已经能够像这样在单个列上定义一个 UNIQUE 约束:

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.但是我需要在两列(例如: FooBar )上定义一个 UNIQUE 约束,而我无法在columns参数中表达这一点。 (The type of the argument is System.Linq.Expressions.Expression<Func<TColumns,object>> ) (参数的类型是System.Linq.Expressions.Expression<Func<TColumns,object>>

How do I define a UNIQUE constraint on two or more columns using the CreateTableBuilder class?如何使用CreateTableBuilder class 在两列或多列上定义唯一约束?

Try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架核心-唯一约束 - Entity Framework Core - Unique Constraint 使用迁移与实体框架核心 - Using Migrations with Entity Framework Core .net core 2 实体框架迁移不起作用 - .net core 2 entity framework migrations not working 使用实体框架在 .NET Core 3.1 中进行迁移后,如何更新数据库 model? - How can I update the database model after doing a migration in .NET Core 3.1 using Entity Framework? 使用UseInMemoryDatabase的实体框架核心迁移错误 - Entity Framework Core migrations error using UseInMemoryDatabase 将 Fody Costura 与 Entity Framework Core 迁移一起使用 - Using Fody Costura with Entity Framework Core migrations 独特的约束实体框架 - Unique constraint entity framework C# - 使用 Entity Framework Core 3 HasConversion 将字段转换为 JSON in.Net Core 3.1 - C# - Using Entity Framework Core 3 HasConversion to convert a field to JSON in .Net Core 3.1 如何在 Entity Framework Core 3.1 中对自定义对象执行原始 SQL 查询,而无需迁移想要创建表? - How do I execute a raw SQL query to a custom object in Entity Framework Core 3.1, without migrations wanting to create a table? 在没有实体框架和迁移的ASP.NET Core MVC应用程序中使用ASP.NET标识 - Using ASP.NET Identity in an ASP.NET Core MVC application without Entity Framework and Migrations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM