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

让人想犯罪 __ 提交于 2019-12-06 14:01:24

问题


My context is =>

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

1) User Table

2) Role Table

3) UserRole Table - A new linked table created automatically

Model for User is =>

Model for Role is =>

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

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

can someone have any idea


回答1:


// 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().



来源:https://stackoverflow.com/questions/37561269/insert-update-data-to-many-to-many-entity-framework-how-do-i-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!