我使用以下RIA Services調用來註冊並返回Project
實體。爲什麼實體框架應該在更新時插入?
// On Server; inside RIA Domain Service
[Invoke]
public Project CreateNewProject(String a_strKioskNumber)
{
Decimal dProjectID = ObjectContext.RegisterProjectNumber(a_strKioskNumber)
.FirstOrDefault() ?? -1m;
// Tried this but it returned zero (0)
//int nChanged = ObjectContext.SaveChanges();
var project = (from qProject in ObjectContext.Projects.Include("ProjectItems")
where qProject.ID == dProjectID
select qProject)
.FirstOrDefault();
if (project == null)
return null;
return project;
}
正如你所看到的,它調用了一個返回項目ID的存儲過程。它使用此ID來查找Project
實體本身並將其返回。當Project
實體返回給客戶端時,它被分離。我將它附加到DomainContext
並修改它。
// At Client
_activeProject = a_invokeOperation.Value; // <-- Detached
_context.Projects.Attach(_activeProject); // <-- Unmodified
if (_activeProject != null)
{
_activeProject.AuthenticationType = "strong"; // <-- Modified
_activeProject.OwnerID = customer.ID;
_projectItems.Do(pi => _activeProject.ProjectItems.Add(pi));
_activeProject.Status = "calculationrequired";
}
此時它的實體狀態爲Modified
。當我提交更改時,它會給我一個有關UNIQUE KEY違例的例外,就好像它試圖插入它而不是更新它。
// At Client
_context.SubmitChanges(OnProjectSaved, a_callback);
我對所有操作使用相同的DomainContext
實例。爲什麼這不適用?
怎麼回事?這很令人沮喪。
編輯:
我想這(傑夫的建議):
[Invoke]
public void SaveProject(Project a_project)
{
var project = (from qProject in ObjectContext.Projects
where qProject.ID == a_project.ID
select qProject)
.FirstOrDefault();
project.SubmitDate = a_project.SubmitDate;
project.PurchaseDate = a_project.PurchaseDate;
project.MachineDate = a_project.MachineDate;
project.Status = a_project.Status;
project.AuthenticationType = a_project.AuthenticationType;
project.OwnerID = a_project.OwnerID;
project.ProjectName = a_project.ProjectName;
project.OwnerEmail = a_project.OwnerEmail;
project.PricePerPart = a_project.PricePerPart;
project.SheetQuantity = a_project.SheetQuantity;
project.EdgeLength = a_project.EdgeLength;
project.Price = a_project.Price;
project.ShipToStoreID = a_project.ShipToStoreID;
project.MachiningTime = a_project.MachiningTime;
int nChangedItems = ObjectContext.SaveChanges();
}
它沒有絕對沒有。它沒有保存該項目。
「當我提交更改它給了我一個異常」 – BentOnCoding 2011-05-27 20:27:32
你確定的唯一鍵違規正被項目實體造成的?您將添加到活動項目中的項目項目是什麼,它們來自哪裏?我假設錯誤信息告訴你到底是什麼造成的,但我只是想我會確認。 – 2011-05-31 14:35:45
您是否驗證過在客戶端上所做的更改是否包含在服務器調用中?如果他們是,那麼我不知道爲什麼它什麼也沒做。 – 2011-05-31 17:30:53