簡體   English   中英

當IDENTITY_INSERT設置為OFF時,無法在表'MyTableName'中為標識列插入顯式值

[英]Cannot insert explicit value for identity column in table 'MyTableName' when IDENTITY_INSERT is set to OFF

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

如果您需要在ID上插入一個值,請嘗試以下操作

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

當您添加具有ID的實體時,EF會出現此錯誤。 通常,該實體已經存在於數據庫中。 要修改實體,請使用以下示例:

_context.TestManyToMany.Add(myManyToMany);

改成

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

如果要執行此操作,則當id SET IDENTITY_INSERT dbo.YOUR_TABLE_NAME ON;標識列時,您需要運行SET IDENTITY_INSERT dbo.YOUR_TABLE_NAME ON; 為它工作。 這使您可以將ID插入“身份”列。 但是,在向帶有標識列的表中插入新行時,無需指定ID :)

還是您要對已有的行進行更新?

研究此站點后:

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

通過使用List和AddRange

我解決了我的問題,請參見下面的“創建函數”代碼,它可以完美運行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM