This seems like it should be quite obvious but something about the entity framework is confusing me and I cannot get this to work.
Quite simply, I have three tables where the Id values are identity columns: Users (userId, username) Categories (categoryId, categoryName) JoinTable (UserId, CategoryId) composite.
In the entities designer (this is .net 4.0), when I import these tables, as expected the join table does not appear but Users and Categories show a relationship. The following code:
var _context = new MyContext();
var myUser = new User();
myUser.UserName = "joe";
var myCategory = new Category();
myCategory.CategoryName = "friends";
_context.Users.AddObject(myUser);
myUser.Categories.Add(myCategory);
var saved = _context.SaveChanges();
Returns an error of (though nothing was added to the database):
An item with the same key has already been added.
If I add the following before saving:
_context.Categories.AddObject(myCategory);
myCategory.Users.Add(myUser);
I get the same error and nothing saved to the db. If I save the myUser and myCategory object before trying to associate them, they both save, but the second save throws an error, with nothing added to the join table:
Cannot insert the value NULL into column 'UserId', table '...dbo.JoinTable'; column does not allow nulls. INSERT fails. The statement has been terminated.
I'm clearly failing to understand how many to many relationships are inserted. What am I missing?