问题
I have an mvc project with database first entityframework. In Project I have 3 tables.
Users >>> UsersInRoles <<< Roles with many to many relationship.
and my CreateUser codes below;
public bool CreateUser(string email, string password, string birthday,string firstname,string lastname)
{
bool result;
var dogumgunu = Convert.ToDateTime(birthday);
var sifre = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "sha1");
var confirmation = CreateConfirmationToken(email);
try
{
var user = new User
{
UserName = email,
Password = sifre,
UserJoinDate = DateTime.Now,
UserBirthDay = dogumgunu,
UserConfirmationToken = confirmation,
UserID = Guid.NewGuid(),
MemberFirstName = firstname,
MemberLastName = lastname
};
var role = new Role
{
RoleName = "Client"
};
user.Roles.Add(role); //problem is here!!!!!!!!!
_bb.Users.AddObject(user);
_bb.SaveChanges();
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
In this code I am new user creating. And I am adding a role. But This code include a new Role in Roles table. I dont want to this. I want to just add UsersInRoles table a new user. What is wrong? Thanks for reply.
回答1:
Swap these two lines:
_bb.Users.AddObject(user);
user.Roles.Add(role);
because AddObject
converts the whole object graph to the Added
state. If you add the role afterwards, its state will remain Unchanged
.
And you should fetch the role from the database first or create a Role
object that only has an existing RoleId
. (A so called stub entity).
So in stead of new Role
you could do
var role = _bb.Roles.Single(r => r.RoleName == "Client");
来源:https://stackoverflow.com/questions/16786945/mvc-entity-framework-many-to-many-user-and-role-insert