2011-06-01 71 views
1

我正在使用Web服務的項目。 Web服務使用linq-to-entities與mysql數據庫進行通信。目前,我正在將linq實體返回給Windows客戶端,客戶端上的實體更新,更改描述,品牌,發佈日期等屬性。我現在試圖將這些更新的對象返回給Web服務並在數據庫中更新它們使用attach方法,但它不起作用。在數據庫中更新這些對象的最簡單方法是什麼?更新Web服務上的linq對象

目前代碼:

Web服務:

public class MobilePartService : System.Web.Services.WebService 
{ 

    MobilePartsEntities _DataContext = new MobilePartsEntities(); 

    [WebMethod] 
    public List<Mobile> GetMobiles() 
    { 
     return _DataContext.Mobiles.ToList(); 
    } 

    [WebMethod] 
    public void UpdateMobile(Mobile prMobile) 
    { 
     _DataContext.Attach(prMobile); 
     _DataContext.SaveChanges(); 
    } 

} 

客戶端更新代碼:

_Mobile.Brand = txtBrand.Text; 
_Mobile.Decription = txtDescription.Text; 
_Mobile.ModelNumber = txtModelNumber.Text; 
_Mobile.ReleaseDate = Convert.ToDateTime(txtReleaseDate.Text);  
clsGlobal.Service.UpdateMobile(_Mobile); 

回答

1

你需要做的AttachSaveChanges電話之間別的東西。 See this link,它有這個例子:

context.SalesOrderDetails.Attach(updatedItem); 
    // Check if the ID is 0, if it is the item is new. 
    // In this case we need to chage the state to Added. 
    if (updatedItem.SalesOrderDetailID == 0) 
    { 
     // Because the ID is generated by the database we do not need to 
     // set updatedItem.SalesOrderDetailID. 
     context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added); 
    } 
    else 
    { 
     // If the SalesOrderDetailID is not 0, then the item is not new 
     // and needs to be updated. Because we already added the 
     // updated object to the context we need to apply the original values. 
     // If we attached originalItem to the context 
     // we would need to apply the current values: 
     // context.ApplyCurrentValues("SalesOrderDetails", updatedItem); 
     // Applying current or original values, changes the state 
     // of the attached object to Modified. 
     context.ApplyOriginalValues("SalesOrderDetails", originalItem); 
    } 
    context.SaveChanges();