ef-Code-First one-to-many optional delete throws exception:primary key value cannot be deleted

Jan 3, 2014 at 8:04 PM
Hi
I am trying out your library, but have a problem ,i even created a post at stackoverflow
http://stackoverflow.com/questions/20909935/ef-code-first-one-to-many-optional-delete-throws-exceptionprimary-key-value-can

I tried to delete a city using this method but it fails.
 var city = _unitOfWork.Repository<City>().Query()
                .Include(c => c.Districts.Select(d => d.Users))
                .Filter(c => c.CityName.Equals(cityName, StringComparison.InvariantCultureIgnoreCase))
                .Get().FirstOrDefault();

_unitOfWork.Repository<City>().Delete(city);
when i call save exception is thrown

Test method DataAccess.Test.Tests.UserDataServiceTest.Delete_city_also_casscade_districts_too_but_not_users threw exception:
System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

i even tried to delete this way but same exception.
var city = _unitOfWork.Repository<City>().Query()
                .Include(c => c.Districts.Select(d => d.Users))
                .Filter(c => c.CityName.Equals(cityName, StringComparison.InvariantCultureIgnoreCase))
                .Get().FirstOrDefault();

            if (city != null)
            {
                foreach (var district in city.Districts)
                {
                    foreach (var user in district.Users.ToList())
                    {
                        user.DistrictId = null;
                        user.District = null;
                        user.ObjectState = ObjectState.Modified;

                        _unitOfWork.Repository<User>().Update(user);
                    }

                    district.Users.Clear();
                    district.ObjectState = ObjectState.Deleted;

                    _unitOfWork.Repository<District>().Update(district);
                }

                _unitOfWork.Repository<City>().Delete(city);
            }
regards
Coordinator
Apr 7, 2014 at 2:27 AM
Edited Apr 7, 2014 at 2:27 AM
This is an EF use case and not really the framework and looks like you received your answers on Stack Overflow http://stackoverflow.com/questions/20909935/ef-code-first-one-to-many-optional-delete-throws-exceptionprimary-key-value-can.
Marked as answer by lelong37 on 4/6/2014 at 6:27 PM