简体   繁体   中英

How do I edit WCF Data Service objects with ASP.NET MVC 2?

I don't want to put any more code into my controller than I have to.

This works:

    //
    // POST: /Duty/Edit/5

    [HttpPost]
    public ActionResult Edit(Duty Model)
    {
        Duty Attached = (from Duty d in ctx.Duties
                         where d.Id == Model.Id
                         select d).Single();
        Attached.Designation = Model.Designation;
        Attached.Instruction = Model.Instruction;
        Attached.OccasionId = Model.OccasionId;
        Attached.Summary = Model.Summary;
        ctx.UpdateObject(Attached);
        ctx.SaveChanges();
        return RedirectToAction("Index");
    }

But, I don't want to have to type every property.

This fails:

    //
    // POST: /Duty/Edit/5

    [HttpPost]
    public ActionResult Edit(Duty Model)
    {
        ctx.AttachTo("Duty", Model);
        ctx.UpdateObject(Model);
        ctx.SaveChanges();
        return RedirectToAction("Index");
    }

It throws a System.Data.Services.Client.DataServiceClientException:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <code></code>
  <message xml:lang="en-US">Resource not found for the segment 'Duty'.</message>
</error>

Why? How should I write this?

try this it might work:

ctx.AttachUpdated(Model);
ctx.SaveChanges();

This will tell data context that every property has been updated.

Guessing from your code the entity set is actually called "Duties". So your code should look like: // // POST: /Duty/Edit/5

[HttpPost] 
public ActionResult Edit(Duty Model) 
{ 
    ctx.AttachTo("Duties", Model); 
    ctx.UpdateObject(Model); 
    ctx.SaveChanges(); 
    return RedirectToAction("Index"); 
} 

(The first parameter for the AttachTo method is the entity set name, not the name of the entity type.) Note that in order for this to work, you must be sure that the entity in question already exists on the server (that is entity with the same key property values). This will issue a PUT request to that entity, and if it doesn't exist it will fail with 404.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM