Entity Framework code first with data annotations 是否可以同时拥有一个主键和组合键?

Is it possible to have one primary key and composite key at the same time in Entity Framework code first with data annotations?

public class Test
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TestId { get; set; }

    [Column(Order = 0)]
    public string TestName { get; set; }

    [Column(Order = 1)]
    public string TestVersion { get; set; }

    public string TestRef { get; set; }
}

上面的结果应该是下面的 SQL

CREATE TABLE [dbo].[Test]
(
    [TestId] INT NOT NULL IDENTITY(1,1),
    [TestName] VARCHAR(40) NOT NULL, 
    [TestVersion] VARCHAR(70) NOT NULL,
    [TestRef] VARCHAR(70) NOT NULL,  
    CONSTRAINT [dbo_Test_PK] PRIMARY KEY CLUSTERED ([TestId] ASC),
    CONSTRAINT [CK_Test_TestNameTestVersion] UNIQUE ([TestName], [TestVersion]), 
    CONSTRAINT [CK_Test_TestRef] UNIQUE ([TestRef])
)

TestNameTestVersion 组合应该是唯一的,TestRef 独立应该是唯一的。

如何使用 EF fluent api 实现此目的?

更新:为 EF 添加了数据库的屏幕截图,并单独 运行 上述查询。

dbo.Test 使用 EF 创建,dbo.TestWithSQL 使用查询

创建

是的,您可以使用 Index 属性来添加点,如下所示:

public class Test
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TestId { get; set; }

    [Column(Order = 0),
        Index("CK_Test_TestNameTestVersion", IsUnique = true, Order = 1)]
    public string TestName { get; set; }

    [Column(Order = 1),
        Index("CK_Test_TestNameTestVersion", IsUnique = true, Order = 2)]
    public string TestVersion { get; set; }

    [Index("CK_Test_TestRef", IsUnique = true)]
    public string TestRef { get; set; }
}

或者您可以像这样使用 Fluent API:

this.Property(c => c.TestRef)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute("CK_Test_TestRef") { IsUnique = true }
    );

this.Property(c => c.TestName)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute("CK_Test_TestNameTestVersion", 1) { IsUnique = true }
    );
this.Property(c => c.TestVersion)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute("CK_Test_TestNameTestVersion", 2) { IsUnique = true }
    );