简体   繁体   English

ASP.NET webapi odata put,属性“ID”是对象的关键信息的一部分,无法修改

[英]ASP.NET webapi odata put, The property 'ID' is part of the object's key information and cannot be modified

I am a nooby with ASP.NET webapi, and this is a very simple situation that i am stuck in. 我是ASP.NET webapi的小说,这是一个非常简单的情况,我被困在。

I am using webapi+odata 我正在使用webapi + odata

My Model: 我的型号:

public class CategoryModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ParentID { get; set; }
}

My Auto Generated Controller's put method: 我的自动生成控制器的put方法:

public async Task<IHttpActionResult> Put([FromODataUri] int key, Delta<CategoryModel> patch)
{
    Validate(patch.GetEntity());

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    CategoryModel categoryModel = await db.Category.FindAsync(key);
    if (categoryModel == null)
    {
        return NotFound();
    }

    patch.Put(categoryModel);

    try
    {
        await db.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!CategoryModelExists(key))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return Updated(categoryModel);
}

And my jquery ajax 而我的jquery ajax

jQuery.ajax(
        {
          url       : '/api/Category(3)',
          data      : { Name:'New Category' },
          method    : 'PUT',
          headers   : {
            Accept        : 'application/json',
          },
          statusCode: {
            401: () => {
              console.log('handle the unautherized here');
            },
          },
          beforeSend: (jqXHR, settings) => {},
          error     : (jqXHR, textStatus, errorThrown) => {
            //TODO do some global error reporting

            Util.Error(JSON.parse(jqXHR.responseText));
            resolve(null);
          },
          success   : (data, textStatus, jqXHR) => {
            resolve(data);
          },
          complete  : (jqXHR, textStatus) => {}
        }
      );

and the error : 和错误:

{
  "odata.error": {
    "code": "",
    "message": {
      "lang": "en-US",
      "value": "An error has occurred."
    },
    "innererror": {
      "message": "The property 'ID' is part of the object's key information and cannot be modified. ",
      "type": "System.InvalidOperationException",
      "stacktrace": "   at System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInProperty(Int32 ordinal, Boolean detectOnlyComplexProperties, Boolean detectOnly)\r\n   at System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInProperties(Boolean detectOnlyComplexProperties)\r\n   at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChangesInScalarAndComplexProperties(IList`1 entries)\r\n   at System.Data.Entity.Core.Objects.ObjectStateManager.DetectChanges()\r\n   at System.Data.Entity.Core.Objects.ObjectContext.DetectChanges()\r\n   at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)\r\n   at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate)\r\n   at System.Data.Entity.Internal.InternalContext.GetStateEntries()\r\n   at System.Data.Entity.Infrastructure.DbChangeTracker.Entries()\r\n   at System.Data.Entity.DbContext.GetValidationErrors()\r\n   at System.Data.Entity.Internal.InternalContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n   at System.Data.Entity.Internal.LazyInternalContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n   at System.Data.Entity.DbContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n   at System.Data.Entity.DbContext.SaveChangesAsync()\r\n   at Notifier.Controllers.CategoryController.<Put>d__3.MoveNext() in E:\\csharp\\notifier\\Notifier\\Notifier\\Controllers\\CategoryController.cs:line 66\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
    }

GET and POST works ok, but PUT and PATCH giving me this error. GETPOST工作正常,但是PUTPATCH给了我这个错误。

Help me please ... 请帮帮我 ...

UPDATE : The problem is with this controller's generated code with odata v3, I checked with normal webapi controller and it works just fine, so .... 更新:问题是这个控制器生成的代码与odata v3,我检查与正常的webapi控制器,它工作正常,所以....

在我看来,你正在尝试使用不同于3的Id更新对象,但是你的ajax调用正在发送一个Id = 3,你在该行中进行了硬编码:

url       : '/api/Category(3)',

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 属性“ ID”是对象键信息的一部分,不能在asp.net mvc中进行修改 - The property 'ID' is part of the object's key information and cannot be modified in asp.net mvc 属性“Id”是对象关键信息的一部分,不能修改 - The property 'Id' is part of the object's key information and cannot be modified 属性“ Id”是对象键信息的一部分,不能在“选择”时进行修改 - The property 'Id' is part of the object's key information and cannot be modified ON SELECT 属性ID是对象键信息的一部分,无法修改 - the property id is part of the object's key information and cannot be modified “属性&#39;Modified&#39;是对象关键信息的一部分,无法修改 - "The property 'Modified' is part of the object's key information and cannot be modified 属性“ VersionID”是对象键信息的一部分,无法修改 - Property 'VersionID' is part of the object's key information and cannot be modified 属性“ APPLICATIONID”是对象键信息的一部分,无法修改 - The property 'APPLICATIONID' is part of the object's key information and cannot be modified 属性“ itemId”是对象键信息的一部分,无法修改 - The property 'itemId' is part of the object's key information and cannot be modified 该属性是对象关键信息的一部分,无法修改 - The property is part of the object's key information and cannot be modified 属性“text”是对象的关键信息的一部分,无法修改 - The property 'text' is part of the object's key information and cannot be modified
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM