我有WCF-Rest服务,如您所见:
[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "/EditNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool Edit(News entity);使用此代码:
public class NewsRepository :INewsRepository
{
private readonly DataContext _ctx;
public NewsRepository(DataContext ctx)
{
_ctx = ctx;
}
public bool Add(News entity)
{
try
{
_ctx.News.Add(entity);
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}
public bool Edit(News entity)
{
try
{
_ctx.Entry(entity).State = System.Data.Entity.EntityState.Modified;
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}
}}因此,我在我的客户端调用我的服务来编辑我的实体,如您所见:
News student = new News
{
Id = Guid.Parse("7320D87D-4819-4663-BCF9-2D09F9E4BD70"),
Subject = "aaaaaaaaaaaaaassssssssssss",
ViewerCounter = 3, // removed the "" (string)
MainContent = "fsdsd", // renamed from "Content"
SubmitDateTime = DateTime.Now,
ModifiedDateTime = DateTime.Now,
PublisherName = "sdaadasd",
PictureAddress = "adfafsd",
TypeOfNews = "bbbbb"
};
WebClient Proxy1 = new WebClient();
Proxy1.Headers["Content-type"] = "application/json";
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(News));
serializerToUplaod.WriteObject(ms, student);
byte[] a = Proxy1.UploadData("http://localhost:47026/NewsRepository.svc/EditNews", "PUT", ms.ToArray());所以我运行我的服务和我的客户端应用程序,第二次点击编辑按钮和编辑works.But,我在我的Edit method中得到了这个错误。
Attaching an entity of type 'CMSManagement.Domain.Entity.News' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.发布于 2017-05-29 10:22:25
最终解
public bool Edit(News entity)
{
try
{
News Edited = _ctx.News.Where(i => i.Id == entity.Id).First();
_ctx.Entry(Edited).CurrentValues.SetValues(entity);
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}发布于 2017-05-29 05:15:37
确保没有任何其他实体附加到您的新闻模型,也许它是试图添加一个实体附加到您的新闻实体,只是传递它没有任何子对象,并确保您使用AsNoTracking()在选择该实体。
https://stackoverflow.com/questions/44234725
复制相似问题