2011-01-12 73 views
0

我知道更新外鍵有什麼問題,我似乎無法讓它工作。LINQ to SQL ForeignKeyReferenceAlreadyHasValueException錯誤

我嘗試了當前代碼和註釋掉的行。

Sponsorship mySponsorship = Repository._context.Sponsorships.SingleOrDefault<Sponsorship>((Sponsorship obj) => obj.id == int.Parse(editId) ? true : false); 

     mySponsorship.Name = txbSponsorshipTitle.Text.Trim(); 

     DataClassesDataContext db = new DataClassesDataContext(); 

     // Don't assign just the id 
     Event myValue = db.Events.Single(x => x.EventId == int.Parse(dropEvent.SelectedValue)); 

     int myEvent = myValue.EventId; 
     //int myEvent = db.Events.Single(x => x.EventId == int.Parse(dropEvent.SelectedValue)).EventId; 
     mySponsorship.EventId = myEvent; 
     mySponsorship.Price = decimal.Parse(txbPrice.Text); 
     mySponsorship.description = venuEdit.Content; 

     Repository._context.SubmitChanges(); 

     Response.Redirect("Sponsorshiplisting.aspx"); 

回答

1

嘗試分配event對象時,它自身不是EventID

Event myValue = db.Events.Single(x => x.EventId == int.Parse(dropEvent.SelectedValue)); 
mySponsorship.Event = myValue ; 

,你可能認爲mySponsorshipevent必須來自相同的datacontext否則LINQ將創建一個同一事件實體添加到您指定的實體並將其插入到數據庫中

+0

是的,您必須設置額外的鏈接屬性LinqToSql生成的,你不能設置ID。 – rtpHarry 2011-01-12 22:45:11