我是C#的新手,正在使用OData和Owinselfhost,问题是当我尝试对我的Object Person进行更新时总是收到此错误消息
The context is not currently tracking the entity
我的控制器
[HttpPut]
[Route()]
// PUT api/people/5
public IHttpActionResult Put([FromBody]Person value)
{
Console.WriteLine("Value updated " + value.LastName);
var result = api.updatePerson(value);
if (result == false)
return BadRequest("An error occurred");
return Ok("Person updated");
}
API服务
public bool updatePerson(Person p)
{
try
{
var ctx = GetAppControlContext();
Person person = new Person();
person = ctx.People.Where(ps => ps.Id == p.Id).SingleOrDefault();
if (person != null)
{
//person.FirstName = p.FirstName;
person = p;
Console.WriteLine("Name" + person.FirstName);
ctx.UpdateObject(person);
ctx.SaveChanges();
}
Console.WriteLine("person updated");
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
PS 只有当我像这样逐个字段分配给人时才起作用
public bool updatePerson(Person p)
{
try
{
var ctx = GetAppControlContext();
Person person = new Person();
person = ctx.People.Where(ps => ps.Id == p.Id).SingleOrDefault();
if (person != null)
{
person.FirstName = p.FirstName;
person.LastName= p.LastName;
person.age= p.age;
Console.WriteLine("Name" + person.FirstName);
ctx.UpdateObject(person);
ctx.SaveChanges();
}
慕侠2389804
相关分类