本文介绍了如何使用EF 6 Fluent Api添加复合唯一键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表(Id,名称,Itemst,Otherproperties),Id是主键,我想要一个唯一的复合键(名称,Itemst)。

I have a table (Id, name, itemst, otherproperties), Id is the primary key and I want a unique composite key (name, itemst). How can I add this using code first either by fluent API (preferred) or annotation?

推荐答案

下面是一个示例,展示了如何通过流畅的API创建一个复合唯一密钥。组合键由ProjectId和SectionOdKey组成。

Here is an example showing how to create a composite unique key via fluent API. The composite key consists of ProjectId and SectionOdKey.

public class Table
{
    int Id{set;get;}
    int ProjectId {set;get;}
    string SectionOdKey{set;get;}
}

public class TableMap : EntityTypeConfiguration<Table>
{
   this.Property(t => t.ProjectId).HasColumnName("ProjectId")
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 1){IsUnique = true}));
   this.Property(t => t.SectionOdKey).HasColumnName("SectionOdKey")
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 2){IsUnique = true}));
}

这篇关于如何使用EF 6 Fluent Api添加复合唯一键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 02:43