I am trying to add a new user (model) which includes a Role(model). My View includes a DropDownListFor which contains a list of roles. I am always getting an Exception when trying to finally add the user to the database.

View:

@model Keba.Data.EF.User
@{
    ViewBag.Title = "Add User";
    List<SelectListItem> roles = new List<SelectListItem>();

}
<h2>Add</h2>
@using (Html.BeginForm("AddUser", "User", FormMethod.Post,
                                      new { enctype = "multipart/form-data" }))
{
    <table>
        <tr><th>@Html.LabelFor(model => model.UserName)</th><td>@Html.EditorFor(model => model.UserName)</td></tr>
        <tr><th>@Html.LabelFor(model => model.Password)</th><td>@Html.EditorFor(model => model.Password)</td></tr>
        @Html.HiddenFor(model => model.MailAdress)
        <tr>
            <th>Roles</th>
            <td>
               @Html.DropDownListFor(x => x.Role.RoleId, new SelectList(ViewBag.roles, "RoleId", "RoleName"))

            </td>
        </tr>
    </table>
    <input name="add" type="submit" value="add" />
    <input name="cancel" type="submit" value="cancel" />
}

Controller:

 [HttpPost]
        public ActionResult AddUser(User user)
        {
            if (Request.Form["add"] != null)
            {
                user.Role = RoleModel.Instance.getRoles().Where(x => x.RoleId == user.Role.RoleId).FirstOrDefault();
                UserModel.Instance.AddUser(user);
            }
            return RedirectToAction("Index");
        }

Model:

public void AddUser(User user)
        {
            using(var db = new KebaContext())
            {
                if (user != null)
                {
                    user.MailAdress = "";
                    db.UserSet.Add(user);//Exception
                    db.SaveChanges();
                }

            }
        }

Exception:

{System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
   at System.Data.Entity.Core.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity)
   at System.Data.Entity.Core.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
   at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
   at System.Data.Entity.Core.Objects.DataClasses.EntityReference.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
   at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
   at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
   at System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
   at System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
   at System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
   at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClassd.<Add>b__c()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   at System.Data.Entity.DbSet`1.Add(TEntity entity)
   at KebaProject.Models.UserModel.AddUser(User user) in c:\Users\s1310307080\Source\Repos\KebaProject2\KebaProject\KebaProject\Models\UserModel.cs:line 92
   at KebaProject.Controllers.UserController.AddUser(User user) in c:\Users\s1310307080\Source\Repos\KebaProject2\KebaProject\KebaProject\Controllers\UserController.cs:line 71
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()}

Related posts

Recent Viewed