POCO, Entity Insert Error in many to many relation
I have a little problem. When i'll add a new item into my databse(EF) i had a UpdateEception : Unable to update the EntitySet 'UserRoles' because it has a DefiningQuery and no element exists in the element to support the current operation.
I have a very small table.
Users :
- [PK] UserID
- Login
- Password
- Email
- IsActive
Roles :
- [PK] RoleID
- Name
UserRoles :
- [FK] UserID
- [FK] RoleID
Get method
User u = db.Users.Single(x => x.Login == "scott");
works fine, but insert not :/ I try a lots of way. I try add 开发者_运维知识库PK to UserRoles, it work, but not like it will be. The relations will be many -> one -> many, not many to many and i must have a one additional class. I don't know how to fix this.
My Entity Class is too very simple. The List in role class and List in user class are virtual.
public class TestDBEntity : ObjectContext
{
public ObjectSet<Role> Roles { get; set; }
public ObjectSet<User> Users { get; set; }
public TestDBEntity()
: base("name=TestDBEntities", "TestDBEntities")
{
ContextOptions.LazyLoadingEnabled = true;
this.Roles = CreateObjectSet<Role>();
this.Users = CreateObjectSet<User>();
}
}
You must create composite key (UserID, RoleID) in your UserRoles table. There is no other way because without defined primary key the table is mapped as readonly view. It will still model as many-to-many relationship but you will propably have to first remove your entities from model and add them again by update from database.
精彩评论