Entity Framework中Remove、Modified实体时,在修改或删除时引发主键冲突的问题

问题:

try
{
string fileId = context.NewsT.Where(t => t.Id == Model.Id).FirstOrDefault().FileId;
string filePath = context.FilesT.Where(t => t.Id == fileId).FirstOrDefault().Filepath;
var file = context.FilesT.FirstOrDefault(m => m.Id == fileId);
context.NewsT.Remove(Model);
context.FilesT.Remove(file);
var i = context.SaveChanges();
//删除文件
FilesHelper.DeleteFiles(ConfigHelper.GetSectionValue("filePath") + filePath);
result.ErrorCode = "1";
result.Message = "API调用成功";
httpResponseMessage.StatusCode = HttpStatusCode.OK;
}
catch (Exception e)
{
result.ErrorCode = "-999";
result.Message = e.Message;
httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
}

ERROR:Attaching an entity of type 'Entity.TableClass' 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.

原因:主键冲突了

解决方案:

将 string fileId = context.NewsT.Where(t => t.Id == Model.Id).FirstOrDefault().FileId;修改为 string fileId = context.NewsT.AsNoTracking().Where(t => t.Id == Model.Id).FirstOrDefault().FileId;//AsNoTracking是预加载,因为ef本身是懒加载(延迟加载),所以如果这里不用预加载,到执行修改时会报model.id冲突错误,所以要用预加载

转载于:https://www.cnblogs.com/qingfenglin/p/10640766.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值