2012-02-02 65 views
1

我試圖更新外鍵的初學者,但它顯示了這個錯誤LINQ到SQL錯誤的更新外鍵

無法隱式轉換類型「DynaDNS.DAO.GroupDetail」到 「long

HostDNSDetail GroupId- FK爲Groupdetails HostDNSId

GroupDetails 的GroupId - PK

public bool UpdateHostDns(HostDNSDetail HostObj) 
{ 
DynaDBDataContext ctx = GetDataContext(); 

var ExistingDns = (from HostDNS in ctx.HostDNSDetails 
      where (HostDNS.HostDNSId) == (HostObj.HostDNSId) 
      select HostDNS).FirstOrDefault(); 

    if (ExistingDns != null) 
    { 
     ExistingDns.GroupId = ctx.GroupDetails.Single(Existing =>Existing.GroupId == HostObj.GroupId); 

    // i m trying to update from the value from "HostObj.GroupId". 
    } 
} 

回答

3

您正在嘗試使用GroupDetails.Single選擇整個對象。因此,而不是:

ExistingDns.GroupId = ctx.GroupDetails.Single(Existing =>Existing.GroupId == HostObj.GroupId); 

你需要做的是這樣的:

long ExistingDnsId = (from c in ctx.GroupDetails 
         where c.GroupId == HostObj.GroupId 
         select c.GroupId).SingleOrDefault(); 
+0

感謝烏拉圭回合的答覆,但它仍然拋出了同樣的錯誤「System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException:操作無效由於目標的當前狀態 「 – KATy 2012-02-02 11:08:19

+0

哦,我看到你在這裏試圖做什麼...如果你想設置ExistingDns.GroupId,然後嘗試,而不是:ExistingDns = ctx.GroupDetails.Single(Existing = > Existing.GroupId == HostObj.GroupId);您應該設置關聯屬性而不是外鍵。 – TheBoyan 2012-02-02 11:36:35

+0

我發現它,我必須將它設置爲GroupDetails的對象,我的意思是,ExistingDns.GroupDetail = ctx.GroupDetails.SingleOrDefault(c => c.GroupId == HostObj.GroupId); //存在於ExistingDns中的GroupDetail [GroupDetail表的對象]。 – KATy 2012-02-02 11:55:20