首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用fluent API设置唯一约束?

用fluent API设置唯一约束?
EN

Stack Overflow用户
提问于 2014-02-05 17:42:57
回答 4查看 107.9K关注 0票数 189

我正在尝试使用Code First构建EF实体,并使用fluent API构建EntityTypeConfiguration。创建主键很容易,但使用Unique约束就不容易了。我看到一些老帖子建议为此执行原生SQL命令,但这似乎与目的背道而驰。使用EF6可以做到这一点吗?

EN

回答 4

Stack Overflow用户

发布于 2016-07-17 15:02:03

下面是一个可以更流畅地设置唯一索引的扩展方法:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

用法:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

将生成迁移,例如:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}

源:Creating Unique Index with Entity Framework 6.1 fluent API

票数 18
EN

Stack Overflow用户

发布于 2016-05-01 04:41:56

@coni2k的答案是正确的,但是你必须添加[StringLength]属性才能让它工作,否则你会得到一个无效的键异常(示例如下)。

[StringLength(65)]
[Index("IX_FirstNameLastName", 1, IsUnique = true)]
public string FirstName { get; set; }

[StringLength(65)]
[Index("IX_FirstNameLastName", 2, IsUnique = true)]
public string LastName { get; set; }
票数 16
EN

Stack Overflow用户

发布于 2014-02-05 18:08:25

不幸的是,Entity Framework不支持这一点。它在EF6的路线图上,但被推迟了:Workitem 299: Unique Constraints (Unique Indexes)

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21573550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档