2016-02-08 47 views
0
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(); 
      } 

      } 

當調用saveChanges()獲取異常:唯一鍵違規,當看着sql profiler我可以看到,EF 6生成一個更新查詢兩個Kupa對象,但它試圖更新在更新Kupa.uniqueId之前NewKupa.uniqueId更新獨特的財產實體框架

+0

你似乎沒有修改任何'Kupa'的'uniqueId'。 'personToEdit.Kupa.uniqueId'和'personToEdit.NewKupa.uniqueId'的價值是什麼?在這個過程中它們是如何改變的? –

+0

起初:personToEdit.Kupa.uniqueId = 1比修改其值爲null,personToEdit.Kupa.uniqueId = null,比賦予newKupa personToEdit.NewKupa.uniqueId = 1。 –

回答

0

假設你使用SQL Server作爲數據庫服務器發生這種情況,因爲你讓NULL值在該列和NULL = NULLNULL所以,如果你有NULL該列,你會得到錯誤多行。

爲了實現這個SQL語句將是這樣的:

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

然而,要做到這一點在EF有沒有簡單的方法,但在這一個解決辦法SO回答here

+0

該列已被定義爲「WHERE uniqueId IS NOT NULL」,該列中已存在重複的空值,問題是EF在將空值分配給舊uniqueId之前嘗試使用新的uniqueId更新數據庫... 。 –

+0

有人有答案嗎? –

+0

我認爲這也可能是因爲你沒有使用'Include'來添加'Kupa'導航屬性。你能顯示錯誤發生時你使用的確切代碼嗎?如果EF在修改並調用SaveChanges()時沒有跟蹤所有實體,則表達式樹可能與您期望的大不相同。 –