具有childEntity Throw的EFCore添加实体已跟踪相同的密钥

时间:2019-06-19 10:23:26

标签: c# asp.net .net-core ef-core-2.1

我正在尝试将我的代码从ef6更新为efcore,在EF 6中,给孩子错误的前取键值Context.Set.Add()而不是Check key。在Add()之后,将触发关系修复(自动修改FK属性),然后触发SaveChange,但是当Add()将抛出键时,EF Core已被跟踪

Microsoft.EntityFrameworkCore 2.2.4 Pomelo.EntityFrameworkCore.MySql 2.2

var defaultPk = "OneCrud_UnitTest";
            var defaultPk2 = "OneCrud_UnitTest2";
            var item1 = new item { ItemGID = defaultPk,ItemID = defaultPk,TS=DateTime.Now };
            item1.itemDetail = new List<itemDetail>();
            var detail1 = new itemDetail() //itemDetail HasKey(t => new { t.ItemGID,t.LineId});
            {
                GUID = Guid.NewGuid().ToString(),
                ItemGID = defaultPk,//this is foregin key 
                LineId = 1
            };
            item1.itemDetail.Add(detail1);
            unitOfWork.DataContext.Set<item>().Add((item1));
            unitOfWork.Commit();

            var item = itemRepository.GetByID(defaultPk);
            var item2 = new item { ItemGID = defaultPk2 };
            item2.ItemID = item2.ItemGID;
            item2.TS = DateTime.Now;
            item2.itemDetail = new List<itemDetail>();
            item2.itemDetail.Add(new itemDetail {
                ItemGID = defaultPk, //in ef 6 will auto fix up to defaultPk2 after Add(), and not throw exception 
                LineId = 1,
                GUID = Guid.NewGuid().ToString(),
            });
            unitOfWork.DataContext.Set<item>().Add((item2)); // in ef core this line will throw exception "has tracked same key  ItemGID[OneCrud_UnitTest],LineId[1]"
            unitOfWork.Commit();

我可以在调用Add()方法之前禁用保存键检查,还是手动修正外键值

0 个答案:

没有答案