I believe that it is impossible to delete an object without setting the necessary navigation properties when using independent associations. You must load Application from the database, or at least find out the value of the foreign key and attach the Application object with this value:
ApplicationPermission entity = new ApplicationPermission { Id = 1 }; entity.Application = new Application { Id = 5 }; DbContext.Set<ApplicationPermission>().Attach(entity);
The SQL command generated when calling SaveChanges as follows:
exec sp_executesql N'delete [dbo].[ApplicationPermissions] where (([Id] = @0) and ([ApplicationId] = @1))',N'@0 int,@1 int',@0=1,@1=5
As you can see, the query for delete not only asks for the Id for ApplicationPermission , but also ( and ) the foreign key value for ApplicationId . To succeed, you must know and set this FK value by setting up a related object with the same primary key.
The problem does not occur when using foreign key associations:
public class ApplicationPermission { public virtual Application Application { get; set; } public int ApplicationId { get; set; } public int Id { get; set; } }
Mapping:
modelBuilder.Entity<ApplicationPermission>() .HasRequired(x => x.Application) .WithMany() .HasForeignKey(x => x.ApplicationId) .WillCascadeOnDelete(false);
Then you can use your source code without setting the value of the FK ApplicationId property to the correct value (by default it will be 0 )) and without setting the navigation property and deleting the object will work. The SQL command does not care about FK and just asking for Id for ApplicationPermission to delete:
exec sp_executesql N'delete [dbo].[ApplicationPermissions] where ([Id] = @0)',N'@0 int',@0=1
I have no idea why SQL commands differ between the two types of associations.