0

I'm trying to learn EFCF but I stumbled upon a records duplication problem and I can't find solution anywhere on the internet (or I just don't know what to search). The DbContext class is as follows:

public class Database : DbContext
{
    public Database() : base("name=DBconnString")
    {
    }
    public DbSet<Human> People { get; set; }


    public void human_add_new(int _rank, String _name, String _surname)
        {
            Human dummy = new Human(_rank, String _name, String _surname);
            People.Add(dummy);
            SaveChanges();
        }
}

And the human class is as follows:

public class Human
    {
        [Index(IsUnique = true)]
        public Int16 ID { get; set; }
        public int rank { get; set; }
        public String name { get; set; }
        public String surname { get; set; }
    }

Now, the problem is whenever I run my code and it executes this:

human_add_new(3, "Noname", "Noname");

a new record is created, thus creating duplicates in my database (so if I run the code 5 times, 5 identical records will be created). How do I prevent that? [Index(IsUnique = true)] doesn't seem to help here, cause in a larger database it may happen that 2 people have the same name or the same surname.

Here's how it looks like in MS SQL Studio: imgur

Amai
  • 51
  • 2
  • 11

1 Answers1

0

You applied a Unique Index to the ID property - if you want unique names/surnames, you'll have to apply a Unique constraint to them as well.

(According to your imgur picture, IDs are distinct, other fields are the same)

  • But then if I'll try to add 'John Smith' and 'Cathy Smith', adding the latter won't be possible. – Amai Feb 23 '16 at 16:00
  • 1
    Ah, then you need a multi-column index. IndexAttribute has a constructor that takes IndexName - A good answer here - http://stackoverflow.com/a/23090070/2656307 – Null Reference Feb 23 '16 at 16:05