仅在逐步调试时才更新实体框架上的表

时间:2015-05-19 14:58:47

标签: c# asp.net-mvc asynchronous ef-code-first entity-framework-5

我尝试使用公司(提供商)更新我的用户的关系表。当我更新(首先删除旧的相关关系),然后添加选定的。

问题是,如果没有调试,只添加记录,但如果调试一步一步工作正常。有些事情很奇怪,但我不知道是什么。

这是代码

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "UsuarioId,Username,Password,Name,LastName,Email,IsActive, Matricula, Cuit,CP, AddressName,AddressNumber,Telefono1, Telefono2,Movil,destiny")] AppUsers_WrapperPOST applicationUser) 
{    
    var companies = Request.Form["companies"];    

    if (String.IsNullOrWhiteSpace(companies)) 
    {
        ModelState.AddModelError("Companies", "One or more company is required");
        return View();
    } 

    if (ModelState.IsValid) 
    {
        var companiesId = companies.Split(new char[] {','})
            .Select(n = > Convert.ToInt32(n)).ToList();
        var selectedCompanies = db.Companies.Where(
            x = > companiesId.Contains(x.Id) && x.IsActive);
        var usrList = db.AplicationUsers.Where(
            x = > x.UserId == applicationUser.UserId).ToList();
        AppUser usr = new AppUser();

        if (usrList.Any()) 
        {
            usr = usrList.FirstOrDefault();
            var companiesToAdd = selectedCompanies;
            applicationUser.Companies = companiesToAdd;
            CopyClass.CopyObject(applicationUser, ref usr);
            db.Entry(usr).State = EntityState.Modified;
            await db.SaveChangesAsync();
        }

        return RedirectToAction("Index");
    }

    return View(applicationUser);
}

0 个答案:

没有答案