How to insert or update many of the many tables in the .net .NET framework

It seems like this should be perfectly obvious, but something in the structure of the entity is confusing me, and I cannot make it work.

Simply put, I have three tables where Id values ​​are identification columns: Users (userId, username) Categories (categoryId, categoryName) JoinTable (UserId, CategoryId).

In the entity constructor (this is .net 4.0), when importing these tables, as expected, the connection table does not appear, but users and categories show the 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();

It returns an error (although nothing has been added to the database):

An item with the same key has already been added.

If before saving I add the following:

_context.Categories.AddObject(myCategory);
myCategory.Users.Add(myUser);

db. myUser myCategory, , , , :

Cannot insert the value NULL into column 'UserId', table '...dbo.JoinTable'; column does not  allow nulls. INSERT fails. The statement has been terminated.

, . ?

+5
3

SaveChanges() , .

- , . SqlProfiler ADO.NET , , SaveChanges :

insert [dbo].[JoinTable]([UserId]) values (@0) select [CategoryId] from
[dbo].[JoinTable] where @@ROWCOUNT > 0 and [UserId] = @0 and [CategoryId] = scope_identity()

, , JoinTable ( PK ).

EntityModel Model Browser, , CategoryId JoinTable StoreGeneratedPattern Identity, UserId None. EF , PK . MS, , , edmx/ssdl , Identity. StoreGeneratedPattern = "Identity" Property EntityType JoinTable :

:

<Property Name="CategoryId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />

To:

<Property Name="CategoryId" Type="int" Nullable="false" />

, , ( !):

insert [dbo].[JoinTable]([UserId], [CategoryId]) values (@0, @1)
+5

, , - .

Category myCategory = _context.Categories.First(i => i.CategoryID == categoryIDToUse);

, :

Category myCategory = new Category{CategoryID = categoryIDToUse };

(CategorySet) ObjectContext, AttachTo ( , ). . - :

myUser.Categories.Add(myCategory);

SaveChanges(). .

+1

All Articles