2
\$\begingroup\$

Here I am trying to post a company view-model and update and insert according. But I feel I am writing it in wrong way or maybe there's a better approach.

Here's my code

[Route("Master/Company/Post"), HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> CompanyPostAsync(CompanyViewModel model)
    {
        model.CountryList = GetCountries();

        //System.Threading.Thread.Sleep(3000);
        var _viewName = "Companies";
        if (!ModelState.IsValid)
            return View(_viewName, model);

        try
        {
            var find = await con.Companies.FirstOrDefaultAsync(x => x.ID == model.ID);
            var currentUser = CurrentUser();
            if (find != null)
            {
                find.Name = model.Name;
                find.Alies = model.Alies;
                find.Line1 = model.Line1;
                find.Line2 = model.Line2;
                find.City = model.City;
                find.State = model.State;
                find.CountryId = model.CountryId;
                find.ZipCode = model.ZipCode;
                find.POBoxNo = model.POBoxNo;
                find.Telephone = model.Telephone;
                find.Mobile = model.Mobile;
                find.Email = model.Email;
                find.Website = model.Website;
                find.IncorporatedNumber = model.IncorporatedNumber;
                find.IncorporatedDate = model.IncorporatedDate;
                find.IsTaxApplicable = model.IsTaxApplicable;
                find.IsLogoPrintInReport = model.IsLogoPrintInReport;
                find.LogoPath = model.LogoPath;
                find.IsActive = model.IsActive;
                find.SaveCount += 1;

            }
            else
            {
                var company = new Company
                {
                    Name = model.Name,
                    Alies = model.Alies,
                    Line1 = model.Line1,
                    Line2 = model.Line2,
                    City = model.City,
                    State = model.State,
                    CountryId = model.CountryId,
                    ZipCode = model.ZipCode,
                    POBoxNo = model.POBoxNo,
                    Telephone = model.Telephone,
                    Mobile = model.Mobile,
                    Email = model.Email,
                    Website = model.Website,
                    IncorporatedNumber = model.IncorporatedNumber,
                    IncorporatedDate = model.IncorporatedDate,
                    IsTaxApplicable = model.IsTaxApplicable,
                    IsLogoPrintInReport = model.IsLogoPrintInReport,
                    LogoPath = model.LogoPath,
                    IsActive = model.IsActive,
                    SaveCount = 1
                };
                con.Companies.Add(company);
            }

            await con.SaveChangesAsync();
            CallSaved(true);
            return RedirectToAction("Companies", "Master", new { id = find?.ID });
        }
        catch (Exception ex)
        {
            CallSaved(false, ex.Message);
            return View(_viewName, model);
        }


    }
\$\endgroup\$
2
\$\begingroup\$

You can get rid of the redundancy by using the EntityState. You first try to get the SaveCount. Then based on this value you set the State either to Added or Modified. Something like this should work:

    var companySaveCount = await con.Companies.SingleOrDefault(x => x.ID == model.ID)?.SaveCount ?? 0;

    var company = new Company
    {
        ...
        SaveCount = saveCount + 1
    };

    var companyExists = companySaveCount > 0;
    con.Entry(company).State = 
        companyExists
            ? EntityState.Modified;
            : EntityState.Added;    
    }   

    await con.SaveChangesAsync(); 

Alternatively the first query could be just:

var companySaveCount = await con.Companies.Where(x => x.ID == model.ID).Select(x => x.ID).SingleOrDefult();

so that you don't have to get the entire object.

\$\endgroup\$
  • \$\begingroup\$ Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions. Error I am getting \$\endgroup\$ – Siraj M May 4 '18 at 16:39
  • 1
    \$\begingroup\$ My bad I should pass ID also in company model which is key for the company entity \$\endgroup\$ – Siraj M May 4 '18 at 16:49
  • 1
    \$\begingroup\$ FYI: setting entity state Modified is sensitive to data loss by concurrency. \$\endgroup\$ – Gert Arnold May 4 '18 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.