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])
)
TestName
和TestVersion
组合应该是唯一的,TestRef
应该是唯一的。
如何使用EF流畅的api实现这一目标?
dbo.Test是使用EF和dbo创建的.TestWithSQL是使用查询创建的
答案 0 :(得分:1)
是的,您可以使用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 }
);