0

when I try to add in my model some note appear Exception

Here is my CompetitionRepository where I implement method

 public void AddCompetition(Competition competition)
   {
       if (competition.ID == 0)
            _context.Competitions.Add(competition);
       else
            _context.Entry(competition).State = EntityState.Modified;

       _context.SaveChanges();

   }

Controller

[HttpPost]   
    public ActionResult AdminPCreate(string compName, int quantity, DateTime starTime)
    {
        if(ModelState.IsValid)
            _dataManager.Competitions.AddCompetition(
                new Competition
                {
                    ID = 1,
                    Quantity = quantity,
                    StartTime = starTime,
                });
        return View("Competitions",GetCompetitions());
    }

And cshtml Page, maybe I'm doing something wrong

 @using (Html.BeginForm("AdminPCreate", "Home"))
{

    @Html.TextBox("compName",null ,new {@placeholder = "Competition Name"})
    @Html.TextBox("quantity", null, new {@placeholder = "Amount players"})
    @Html.TextBox("starTime", null, new {@placeholder = "Enter beginnig of the match like dd\\mm\\yyyy"})

    <input type="submit" value="Create" class="btn btn-success"/>

I also tried using a lot of solutions including here on that site, such as that because when i try to use that (ObjectStateManager.GetObjectStateEntry(entity)` because my field methods have type different from object

public void AddCompetition(Competition competition)
Community
  • 1
  • 1
Alex
  • 11
  • 6

1 Answers1

0

In the method AdminPCreate of your controller, you have new Competition { ID = 1, [..] }.

That ID valueof 1 makes your repository think it's an existing item, so Entity Framework tries to update the Competition record where ID = 1. That doesn't exist, so your database returns "0 rows affected" and the error is thrown.

I suspect that when you set the ID to 0 instead of 1 in your controller it'll work.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • ok, when i set id to 0 it show me such exception 'Cannot insert the value NULL into column 'Id' – Alex Nov 07 '13 at 06:48
  • @user make sure it is an identity (auto-increment) column. – CodeCaster Nov 07 '13 at 07:29
  • in DB ID is(auto-increment).. and i must make it in my model too? – Alex Nov 07 '13 at 11:59
  • 1
    yes.. the problem was in autoincrement attribue.. i done some foreign keys in table, which blocked main entity ID.. thx, now everything work.. – Alex Nov 07 '13 at 12:25