Home Ask Login Register

Developers Planet

Your answer is one click away!

Omer David February 2016

Update Unique property entity framework

public  class Person
    public int? KupaId { get; set; }

    public Kupa Kupa { get; set; }

    public int? newKupaId { get; set; }

    public Kupa NewKupa { get; set; }

public class Kupa
    public int Id { get; set; } 

    [Index("Ix_uniqueId", IsUnique = true)]
    public int ? uniqueId { get; set; } 

public class MyController:Controller

    public Json EditKupa(Expression<Func<Person,bool>> criteria )
     using (IKupotRepository<Person> _IPersonRepository = new SQlRepository<Person>())
    Person personToEdit=_IPersonRepository.SingleOrDefault(criteria,GetIncludeProperties());
    > //Getting the new kupa obj from db

             newKupa = GetKupa(UniqueId);
   <//changing the unique property to null
             personToEdit.Kupa.ToremId = null;
             personToEdit.Kupa.State = State.Modified;

             personToEdit.NewKupa = newKupa;
>//Assign the unique id property the value that was in the first Kupa

             personToEdit.NewKupa.ToremId = 1;
             personToEdit.newKupaId = newKupa.Id;
             personToEdit.NewKupa.State = State.Modified;



when calling saveChanges() getting an exception :unique key violation , when looking at the sql profiler i can see that EF 6 generates an update query for both the Kupa object but it tries to update the NewKupa.uniqueId before updating the Kupa.uniqueId ?


Mihail Stancescu February 2016

Assuming you are using SQL Server as a database server this is happening because you allow NULL values in that column and NULL = NULL is NULL so if you have multiple rows with NULL on that column you'll get the error.

To implement this in SQL statements will be like this:

ON Kupa(uniqueId)

However, to do this in EF there is no easy way, but there is a workaround in this SO answer here.

Post Status

Asked in February 2016
Viewed 2,031 times
Voted 10
Answered 1 times


Leave an answer

Quote of the day: live life