2011-06-01 72 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();