EF6 codefirst中的唯一多列

我有一个类似于以下内容的电子邮件:

public class Email { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Subject { get; set; } public string Body { get; set; } public string From { get; set; } public DateTime SentOn { get; set; } public List To { get; set; } } 

为了确保唯一性,我在SubjectFromSentOn上创建了一个复合键

这造成了当Subject超过128个字符时validation失败的问题。 所以我只是在它上面放了一个[MaxLength]属性。 但现在它不能成为关键专栏

我该怎么办? 有没有办法确保独特性而不是关键?

如果您使用的是EF 6.1 ,则可以使用多列索引function:

 public class Email { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Index("IX_EmailUniqueness", 1, IsUnique = true)] public string Subject { get; set; } public string Body { get; set; } [Index("IX_EmailUniqueness", 2, IsUnique = true)] public string From { get; set; } [Index("IX_EmailUniqueness", 3, IsUnique = true)] public DateTime SentOn { get; set; } public List To { get; set; } } 

在这里查看此SOpost,您可以添加索引以确保唯一性,作为属性或使用EF FluentAPI 使用流畅的API设置唯一约束?

请注意,您必须使用EF6.1或更高版本。 这是MSDN文章

编辑:

在这里和msdn稍微检查之后,看起来PK和索引键的限制是900字节或更少,因此您将希望使用您的身份作为密钥,并以另一种方式确保唯一性。

举个例子,我尝试手动创建主题列为唯一,长度为4000,我收到此错误:

Warning! The maximum key length is 900 bytes. The index 'UQ__Emails__A2B1D9048E9A2A16' has maximum length of 8000 bytes. For some combination of large values, the insert/update operation will fail. 如果你要做集群密钥选项,你会在创建时得到这个警告(我在每列上做了长度4000) Warning! The maximum key length is 900 bytes. The index 'PK_dbo.Emails' has maximum length of 16012 bytes. For some combination of large values, the insert/update operation will fail. Warning! The maximum key length is 900 bytes. The index 'PK_dbo.Emails' has maximum length of 16012 bytes. For some combination of large values, the insert/update operation will fail. 这真的意味着几乎所有真实世界的参赛作品都会失败。

因此,虽然您可以手动调整128长度限制,但不建议这样做,您很可能会收到错误并丢失数据。 和EF只会让你的密钥长度为128 – 不知道如果你支持它并改变它会怎么做。