在web服务上更新linq对象
本文关键字:linq 对象 更新 web 服务 | 更新日期: 2023-09-27 17:58:01
我正在处理一个使用web服务的项目。web服务使用linq-to实体与mysql数据库进行对话。目前,我正在将linq实体返回到windows客户端,这些实体在客户端上更新,更改描述、品牌、发布日期等属性。我现在正试图将这些更新的对象返回到web服务,并使用attach方法在数据库中更新它们,但它不起作用。更新数据库中这些对象的最简单方法是什么?
当前代码:
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);
您需要在Attach
和SaveChanges
调用之间执行其他操作。请参阅此链接,其中有以下示例:
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();