Unique multiple column in EF6 codefirst

I have a class email that looks like this:

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; }
}

To ensure uniqueness, I made a composite key on Subject, FromandSentOn

This created a problem in which if the object exceeds 128 characters, the check is not performed. So I just put an attribute on it [MaxLength]. But now it cannot be a key column

What should I do? Is there a way to ensure uniqueness without being a key?

+4
source share
2 answers

If you use EF 6.1, you can use Features of several columns :

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; }
}
+3

SO, , EF FluentAPI Constraint API?

, EF6.1 . MSDN

EDIT:

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., , .

, 128, , , , . EF 128 - , , .

0

All Articles