我有一个WCF休息服务,如您所见:
[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());
所以我运行我的服务和我的客户端应用程序,然后单击编辑按钮,我的编辑工作。但是第二次我在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.
确保没有任何其他实体附加到您的新闻模型,也许它正在尝试添加一个附加到您的新闻实体的实体,只需在没有任何子对象的情况下传递它,并确保在选择此实体时使用了AsNoTracking()
。
最终解决方案
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;
}
}