无法为表格中的标识列插入显式值' MyTableName'当IDENTITY_INSERT设置为OFF

时间:2016-03-15 08:11:14

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

我正在使用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; }
}

我的模型2用于插入相关项目ID:

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

4 个答案:

答案 0 :(得分:1)

如果您需要在ID上插入值,请尝试使用

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

答案 1 :(得分:0)

当您使用Id添加实体时,您将收到EF此错误。通常这个实体已存在于DB中。要修改实体,请使用以下示例:

_context.TestManyToMany.Add(myManyToMany);

更改为

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

答案 2 :(得分:0)

如果您想要这样做,当您的id-column是标识列时,您需要运行SET IDENTITY_INSERT dbo.YOUR_TABLE_NAME ON;才能使用它。这使您可以在标识列中插入ID。 但是,在将新行插入带有标识列的表中时,不需要指定ID:)

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

答案 3 :(得分:0)

学习本网站后:

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