Sam
Sam

Reputation: 97

Insert/Update data to Many to Many Entity Framework . How do I do it?

My context is => enter image description here

Using this model via Entity Framework code 1st, data table in database becomes =>

1) User Table

enter image description here

2) Role Table

enter image description here

3) UserRole Table - A new linked table created automatically

enter image description here

Model for User is =>

enter image description here

Model for Role is =>

enter image description here

and my O Data query for inserting record for single User/Role table working properly

enter image description here

Now, what query should I write, when I want to Insert record to UserRole table

can someone have any idea

Upvotes: 1

Views: 332

Answers (1)

smoksnes
smoksnes

Reputation: 10851

// Fetch the user.
var user = await metadataManagentClient.For<User>().FirstOrDefaultAsync(x => x.Name == "Test");


// If you want to add a new role.
var newRole = new Role()
{
    Name = "My new role"
};
user.Roles.Add(newRole); // Adds new role to user.

// If you want to add an existing role
var existingRole = await metadataManagentClient.For<Role>().FirstOrDefaultAsync(x => x.Name == "My Existing Role");
user.Roles.Add(existingRole); // Adds existing role to user.

// Save changes.
metadataManagentClient.SaveChanges();

Or

await metadataManagentClient.SaveChangesAsync();

You might want to set ID as well. But watch out for new Guid() since it generates an empty guid. What you probably want (if you're not using IDENTITY) is Guid.NewGuid().

Upvotes: 1

Related Questions