I have the following scenario, How can i do this without getting the System.InvalidOperationException error.
SomeClass.cs:
using (var eo = new MyEntities())
{
targetRole = (from p in eo.UserRoles
where p.Code == 2
select p).FirstOrDefault();
}
var user = new User
{
UserName = userName,
Password = txtPassword.Text.Trim(),
UserRole = targetRole
};
AnotherClass.AddObject(user);
AnotherClass.cs
public static void AddObject(object poco)
{
using (var eo = new MyEntities())
{
eo.AddObject("Users", poco);
eo.SaveChanges(); //<--- Exceptions Thrown.
}
}
I found the answer myself, I need to attach the targetRole object to the current context:
AnotherClass.cs :