【问题标题】:Cannot insert explicit value for identity column in table 'MyTableName' when IDENTITY_INSERT is set to OFF当 IDENTITY_INSERT 设置为 OFF 时,无法在表“MyTableName”中插入标识列的显式值
【发布时间】:2016-03-15 08:11:14
【问题描述】:

我正在使用 ASP.Net MVC 6

我的控制器功能:

// POST: MyManyToManies/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(MyManyToMany myManyToMany)
{
    if (ModelState.IsValid)
    {


        _context.TestManyToMany.Add(myManyToMany);
        _context.SaveChanges();
        //==========Get Last Inserted ID==============//
        int LastInsertedID = _context.TestManyToMany.Max(c => c.ID);
        string[] agencies = Request.Form["agencies"].ToArray();

        MyManyRelAgency Rel = new MyManyRelAgency();

        foreach (string aitem in agencies)
        {
            int d = int.Parse(aitem);
            Rel.AgencyID = d;
            Rel.MyManyID = LastInsertedID;

            _context.Add(Rel);
            _context.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    return View(myManyToMany);
}

我的模型 1

public class MyManyToMany
{
    public int ID { get; set; }
    public string FirstName { get; set; }
}

用于插入相关商品 ID 的模型 2:

public class MyManyRelAgency
{
    [Key]
    public int ID { get; set; }
    public int MyManyID { get; set; }
    public int AgencyID { get; set; }
}

我的观点:

@model UNTest.Models.MyManyToMany

@{
    ViewData["Title"] = "Create";
 }

<h2>Create</h2>

<form asp-action="Create">
    <div class="form-horizontal">
       <h4>MyManyToMany</h4>
       <hr />
       <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
       <div class="form-group">
           <label asp-for="FirstName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="FirstName" class="form-control" />
               <span asp-validation-for="FirstName" class="text-danger" />
            </div>
        </div>

        <div class="form-group">
        <label class="col-md-2 control-label">Province</label>
        <div class="col-md-10">
            @Html.DropDownList("agencies", (List<SelectListItem>)ViewBag.options, htmlAttributes: new { @class = "form-control",@multiple="multiple" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
        </div>
    </div>
</form>

<div>
   <a asp-action="Index">Back to List</a>
</div>

当我点击插入时出现以下错误:

Cannot insert explicit value for identity column in table 'MyManyRelAgency' when IDENTITY_INSERT is set to OFF

【问题讨论】:

  • 您遇到了 SQL Server 错误,但您没有向我们显示任何 SQL 代码甚至您的任何 ORM 映射信息。
  • 我正在使用 ASP.Net MVC 6,并且我创建了您可以看到的模型类,我想实现多对多关系,但出现错误

标签: c# asp.net entity-framework-6 asp.net-core-mvc


【解决方案1】:

如果你需要在 ID 上插入一个值,试试这个

[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
 public int ID{ get; set; }

【讨论】:

  • 如果您看到我的代码,我只想插入 Rel.AgencyID = d; Rel.MyManyID = LastInsertedID;我设置主键和自动增量的 ID 字段,它给出错误:MyManyID 字段不是主键
  • 您不需要获取 LastInsertedID,当您设置第一个 savechanges() 时,实体 myManyToMany.ID 应该会自动更新。但我认为实体主要是错误的:public class MyManyRelAgency { [Key] public int ID { get; set; } public MyManyToMany MyMany { get; set; } public Agency Agency { get; set; } }
【解决方案2】:

当您添加具有 ID 的实体时,您会在 EF 中收到此错误。通常这个实体已经存在于数据库中。要修改实体,请使用以下示例:

_context.TestManyToMany.Add(myManyToMany);

改成

foreach(var e in myManyToMany)
    _context.Entry(e).State = EntityState.Modified;

【讨论】:

    【解决方案3】:

    如果这是您想要做的事情,当您的 id 列是标识列时,您需要运行 SET IDENTITY_INSERT dbo.YOUR_TABLE_NAME ON; 才能使其工作。这使您可以将 ID 插入标识列。 但是,在具有标识列的表中插入新行时,您不需要指定 ID :)

    或者您是否尝试更新已经存在的行?

    【讨论】:

      【解决方案4】:

      研究本站后:

      http://www.entityframeworktutorial.net/entityframework6/addrange-removerange.aspx

      通过使用 List 和 AddRange

      我解决了我的问题,请参阅下面的 Create Function 代码,它运行良好:

            // POST: MyManyToManies/Create
          [HttpPost]
          [ValidateAntiForgeryToken]
          public IActionResult Create(MyManyToMany myManyToMany)
          {
              if (ModelState.IsValid)
              {
      
      
                  _context.TestManyToMany.Add(myManyToMany);
      
                  _context.SaveChanges();
                  //==========Get Last Inserted ID==============//
                  int LastInsertedID = _context.TestManyToMany.Max(c => c.ID);
                  string[] agencies = Request.Form["agencies"].ToArray();
      
                  //MyManyRelAgency Rel = new MyManyRelAgency();
                  IList<MyManyRelAgency> TheRel = new List<MyManyRelAgency>();
                  foreach (string aitem in agencies)
                  {
                      int d = int.Parse(aitem);
      
                      TheRel.Add(new MyManyRelAgency() { AgencyID = d, MyManyID = LastInsertedID });
                      //Rel.AgencyID = d;
                      //Rel.MyManyID = LastInsertedID;
      
      
      
                  }
                  _context.MyManyToManyRelWithAgency.AddRange(TheRel);
                  _context.SaveChanges();
                  return RedirectToAction("Index");
              }
              return View(myManyToMany);
          }
      

      【讨论】:

      • 这不可能解决您的问题。我确定您还将ID 的列映射更改为身份。
      猜你喜欢
      • 2016-05-13
      • 2016-08-18
      • 2019-03-10
      • 2010-11-22
      • 2011-08-26
      • 2017-12-17
      • 1970-01-01
      相关资源
      最近更新 更多