Omer David February 2016

Update Unique property entity framework

public  class Person
{    
    [Required]
    public int? KupaId { get; set; }

    [ForeignKey("KupaId")]
    public Kupa Kupa { get; set; }

    public int? newKupaId { get; set; }

    [ForeignKey("newKupaId")]
    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;

           _IPersonRepository.SaveChanges();
            }

            }

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 ?

Answers


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:

CREATE UNIQUE NONCLUSTERED INDEX Idx_UniqueId_NotNull
ON Kupa(uniqueId)
WHERE uniqueId IS NOT NULL;

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

Search




Leave an answer