The problem is that the collection role.Permissions
is not loaded before you make changes to it. This is because
It cant't be lazy loaded. To enable lazy loading, add the
virtual
modifier:public virtual ICollection<Permission> Permissions
It isn't loaded eagerly, which can be done by
Include
:from s in db.Roles.Include(r => r.Permissions) ...
So you should do either of these, or both. Eager loading is preferred, because it grabs the data in one query.
The exception isn't too clear. It refers to case where entities don't have primitive foreign key properties, only collections and references to objects. But this only applies to 1-n associations. In the classical Order-Orderline
association, Orderline
may have
public virtual Order Order { get; set; }
which makes this an independent association
and also
[ForeignKey("Order"]
public virtual int OrderId { get; set; }
which turns it into a foreign key association.
But in a many-to-many association the entities can't have these primitive properties, because the foreign keys are in the hidden junction table roles_permissions
. EF could give a more descriptive exception message here.