0

当我尝试在我的模型中添加一些注释时出现异常

这是我实现方法的 CompetitionRepository

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

       _context.SaveChanges();

   }

控制器

[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());
    }

还有cshtml页面,可能我做错了什么

 @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"/>

我还尝试在该站点上使用很多解决方案,包括此处,例如因为 当我尝试使用它时 (ObjectStateManager.GetObjectStateEntry(entity)`,因为我的字段方法的类型与对象不同

public void AddCompetition(Competition competition)
4

1 回答 1

0

AdminPCreate您的控制器的方法中,您有new Competition { ID = 1, [..] }.

IDvalueof1使您的存储库认为它是现有项目,因此 Entity Framework 尝试更新Competition记录 where ID = 1。那不存在,因此您的数据库返回“0 行受影响”并引发错误。

我怀疑当您将其设置ID0而不是1在您的控制器中时,它会起作用。

于 2013-11-06T22:09:16.160 回答