Oracle ODP.Net and EF CodeFirst - SaveChanges Error

强颜欢笑 提交于 2019-11-29 16:12:55

The idea with the Attach() method is that you have an entity that is known to be in the DB but not being tracked by this context, right? My question to you is do you know for sure that this Role here:

Role r = new Role { ID = 1, Name = "Members" };

is something that exists already? If it doesn't, I don't think what you want to do is use

ctx.Roles.Attach(r);

rather it is that you'd write:

ctx.Roles.Add(r);

and then you could turn around and write

User u = new User {
    Login = login,
    Password = password,
    Status = 1,
};

ctx.Users.Add(u);
u.Roles.Add(r);
ctx.SaveChanges();

The issue your first example has is that this new Role is really new to the DB so attaching it isn't what you'd want to do, rather you'd want to Add it.

And the single call to ctx.SaveChanges() should work just fine here.

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