0

我有以下模型。獲取異常「更新實體時無法更改關係,因爲一個或多個外鍵屬性是不可空的」

public class Site 
{ 
    public int Id { get; set; } 
    public string SiteName { get; set; } 
    public string SiteUrl { get; set; } 
    public IEnumerable<SiteBrand> SiteBrands { get; set; } 
} 

public class SiteBrand 
{ 
    public int Id { get; set; } 
    public int SiteId { get; set; } 
    public int BrandId { get; set; } 
    public SiteConfiguration SiteConfiguration { get; set; } 
} 

SiteBrand在SiteId的SiteId上有一個外鍵。

我想以這種方式更新我的網站實體。

public bool Update(Site item) 
{ 
    try 
    { 
     if (item == null) 
      return false; 

     var itemToUpdate = 
      _dbContext.SiteConfigurations.FirstOrDefault(ua => ua.Id == item.Id); 

     if (itemToUpdate == null) 
      return false; 

     itemToUpdate.SiteName = item.SiteName; 

     itemToUpdate.SiteBrands = item.SelectedBrands.Select(
      br => 
      new DataEntities.Siteconfig.SiteBrand {BrandId = br}).ToList(); 

     _dbContext.SaveChanges(); // Save changes. 

     return true; 
    } 
    catch (Exception e) 
    { 
     throw new Exception(e.Message); 
    } 
} 

但上面的代碼拋出以下異常。

操作失敗:無法更改關係,因爲 一個或多個外鍵屬性是不可空的。當 更改爲關係時,相關的外鍵屬性 設置爲空值。如果外鍵不支持空值,則必須定義一個新的關係,外鍵屬性必須爲 分配另一個非空值,或者無關對象必須爲 刪除。

我想我得到這個錯誤,因爲我試圖用清除現有的外鍵條目來更新我的Site實體。我不確定是否正確,也不知道如何解決這個問題。有人可以幫助我嗎?

感謝

+0

它的工作原理,如果你刪除'itemToUpdate.SiteBrands = item.SelectedBrands ...'或將其更改爲'itemToUpdate.SiteBrands = item.SelectedBrands;'? –

回答

0

問題是你是不是值分配給您的SITEID外鍵,因此將被髮送到數據庫爲空(其中你的數據庫的關係不允許)。試着改變你的代碼:

itemToUpdate.SiteBrands = item.SelectedBrands 
           .Select(br => new DataEntities.Siteconfig.SiteBrand 
              { 
               SiteId = item.Id, 
               BrandId = br 
              }).ToList(); 
相關問題