简体   繁体   中英

Entity Framework is deleting the existing items from the collection when I add new

In my project I have Student and Backpack entities. Backpack references Student(one to many). So I have a Student record in DB and it has two backpacks. I am loading the student from DB and getting the backpacks count. In that case it is returning two. When I add a new backpack to the list it is removing the existing two backpacks from the collection. I can't post my code, because of the complexity. Ill try to explain what I am doing. In the Student reference property setter in the Backpack I am checking if the backpack exists in the Student's Backpacks collection. If it not then adding the backpack to the list. And then I am adding the object to Entity Framework context. Here is the code for that:

        if (entity != null && EFContext.Entry(entity).State == EntityState.Detached)
        {
            try
            {
                var entityType = entity.GetType();
                GetObjectContext.AddObject(entityType.Name + "s", entity);
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("Object references between two different object scopes are not allowed"))
                {
                    throw;
                }
            }
        } 

When debugger hits the first line in the posted code, Entity Framework is deleting the existing objects from the list. Here is the call stack:

在此处输入图片说明

I am trying to reproduce the same issue on a simple project but, don't have success yet. Anyone knows why EF will remove my objects from the Collection navigation property?

Please try changing GetObjectContext.AddObject(entityType.Name + "s", entity); to GetObjectContext.AddObject(entity);

I figured out the issue. I had a business logic in my reference navigation property and that was not allowing the reference property value to be set during the loading. That's why when I tried to get the object state it was removing it from the collection. So when I loaded the student with backpacks, Backpack.Student property was null. after making changes to my code reference property was getting set and that fixed the issue I had.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM