0

I tried to create Unique columns in my database with Index but it is not working.It creates everything else but not Email and SSN just leaves as normal columns. Is there some other way to create Unique columns.

    [StringLength(40)]
    [Index("IX_PIndex", 2, IsUnique = true)]
    public string Email { get; set; }


   [StringLength(20)]
   [Index("IX_PIndex", 1, IsUnique = true)]
   public string SSN { get; set; }
  • why do they have the same index name? – Nikki9696 Jul 31 '19 at 21:42
  • possible duplicate https://stackoverflow.com/questions/10614575/entity-framework-code-first-unique-column – Nikki9696 Jul 31 '19 at 21:44
  • Because it says here that they have to have the same. https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations – dsad sdasdas Jul 31 '19 at 21:50
  • So you're trying to do a multi column key? Why do you think the columns look normal? Unique indexes are in the index explorer, not the columns, in sql server UI – Nikki9696 Jul 31 '19 at 21:53
  • to be clear, there will be nothing special about the columns when you're just making a composite key or index. – Nikki9696 Jul 31 '19 at 21:54
  • Sorry for my bad "programming language".I am new in all of this. When I say they look normal I mean I can steel get in database same value under Email or SSN. IDK what do you mean by mult column key but I have primary key and then I want 2 more unique columns Email and SSN so they cant write same value. – dsad sdasdas Jul 31 '19 at 21:57
  • But you used the same index name. That makes them a composite index. Don't do that if you want each one to be unique by itself. – Nikki9696 Jul 31 '19 at 21:58
  • "Indexes that span multiple columns are specified by using the same name in multiple Index annotations for a given table. When you create multi-column indexes, you need to specify an order for the columns in the index. " – Nikki9696 Jul 31 '19 at 21:59
  • Just a second. I will try that now to see if there is any difference. – dsad sdasdas Jul 31 '19 at 22:02
  • you may need to clear your data that violates the unique constraint first. – Nikki9696 Jul 31 '19 at 22:03

1 Answers1

0

From the comments, it seems that you are trying to create a unique index for EACH column. Meaning that no two rows can have the same SSN and no two rows can have the same EMAIL. What you did, however, was create a composite index, which means that no two rows can have the same COMBINATION of SSN and EMAIL.

Solution: remove your syntax that declares them having the same index name. This will make each column a unique in its own right.

Nikki9696
  • 6,260
  • 1
  • 28
  • 23