I'm using EF code first 6.1
with .NET 4
in my application and have following classes in my model(I cut other unrelated parts of diagram. e.g Permission
has other navigations):
My business logic works with detached entities so I'm using RefactorThis.GraphDiff 2.0.1.0
to perform updates.
I want to update an applicationUserInApplication
object, so I get an existing applicationUserInApplication
with its SecurityRole
s from database and return it as a View-Model
then update it and map back it to applicationUserInApplication
using Automapper
(in update operation, I only change SecurityRoles
collection of an applicationUserInApplication
, these SecurityRole
s saved before and I only select them), so I defined following configuration:
_dbContext.UpdateGraph(appUserInApplication, map => map
.OwnedCollection(t => t.SecurityRoles, with=>
with.AssociatedCollection(t=>t.Permissions)
.AssociatedEntity(t => t.ApplicationDescriptor))
.AssociatedEntity(t=>t.ApplicationDescriptor)
.AssociatedEntity(t=>t.AppUser)
.AssociatedEntity(t=>t.UserProfile));
and defined following mapping for AppUserInApplication
in AppUserInApplication_Mapping
class:
this.HasRequired(t => t.AppUser).WithMany(t => t.AppUserInApplications).HasForeignKey(d => d.AppUserId);
this.HasRequired(t => t.Applicationdescriptor).WithMany(t => t.AppUserInApplications).HasForeignKey(d => d.ApplicationId);
this.HasMany(t => t.SecurityRoles).WithMany(t => t.AppUserInApplications)
.Map(m =>
{
m.ToTable("AppUserInApplicationSecurityRole");
m.MapLeftKey("AppUserInApplications_Id");
m.MapRightKey("SecurityRoles_Id");
});
this.HasRequired(t => t.UserProfile).WithMany().HasForeignKey(t=>t.UserProfileId);
After calling above UpdateGraph()
, when I call _dbContext.SaveChange();
I get following error:
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll Additional information: 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.
[Updated]
I also, tried following mapping
_dbContext.UpdateGraph(appUserInApplication, map => map
.AssociatedCollection(t => t.SecurityRoles)
.AssociatedEntity(t => t.Application)
.AssociatedEntity(t => t.UserProfile)
.AssociatedEntity(t => t.AppUser);
But I get same error, yet.
Does anyone know where is the problem?
[Updated]
I uploaded a simplified version of my model, you can get it from https://www.dropbox.com/s/i9dvrb6ebd5wo7h/GraphdiffTest.rar?dl=0