繁体   English   中英

EF6 codefirst中的唯一多列

[英]Unique multiple column in 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<string> To { get; set; }
}

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

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

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

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

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<string> To { get; set; }
}

在这里查看此SO帖子,您可以添加索引以确保唯一性,作为属性或使用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 - 不知道如果你支持它并改变它会怎么做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM