简体   繁体   English

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

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

I am using ASP.Net MVC 6 我正在使用ASP.Net MVC 6

My Controller 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();

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

My Model 1 我的模特1

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

My Model 2 for inserting related items ids: 我的模型2用于插入相关项目ID:

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

My View: 我的观点:

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

When I click on insert I get bellow error: 当我单击插入时,出现以下错误:

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

If you need insert a value on ID, try this 如果您需要在ID上插入一个值,请尝试以下操作

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

You are getting this error with EF when you are adding an entity with Id. 当您添加具有ID的实体时,EF会出现此错误。 Usually this entity is already exists in DB. 通常,该实体已经存在于数据库中。 To modify an entity use example below: 要修改实体,请使用以下示例:

_context.TestManyToMany.Add(myManyToMany);

change to 改成

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

If this is something you want to do, when your id-column is an identity column, you need to run SET IDENTITY_INSERT dbo.YOUR_TABLE_NAME ON; 如果要执行此操作,则当id SET IDENTITY_INSERT dbo.YOUR_TABLE_NAME ON;标识列时,您需要运行SET IDENTITY_INSERT dbo.YOUR_TABLE_NAME ON; for it to work. 为它工作。 This enables you to insert an ID into the identity column. 这使您可以将ID插入“身份”列。 However, you don't need to specify an ID when inserting a new row into a table with an identity column :) 但是,在向带有标识列的表中插入新行时,无需指定ID :)

Or are you trying to do an update of an already existing row? 还是您要对已有的行进行更新?

After studying this site: 研究此站点后:

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

by using List and AddRange 通过使用List和AddRange

I solved my problem, please see below code for Create Function it works perfect: 我解决了我的问题,请参见下面的“创建函数”代码,它可以完美运行:

      // 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.

相关问题 实体框架:当IDENTITY_INSERT设置为OFF时,无法为表&#39;[table]&#39;中的标识列插入显式值 - Entity Framework: Cannot insert explicit value for identity column in table '[table]' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法为表 [表名] 中的标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF 出现错误:当IDENTITY_INSERT设置为OFF时,无法在表&#39;Table&#39;中为标识列插入显式值 - Getting Error: Cannot insert explicit value for identity column in table 'Table' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法为表&#39;ActivityInstances中的标识列插入显式值 - Cannot insert explicit value for identity column in table 'ActivityInstances' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;Recipe&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;AspNetUsers&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'AspNetUsers' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法在表&#39;candidatedetails&#39;中为identity列插入显式值 - Cannot insert explicit value for identity column in table 'candidatedetails' when IDENTITY_INSERT is set to OFF IDENTITY_INSERT设置为OFF时,EF无法为表“ PATIENT DONOR”中的标识列插入显式值 - EF Cannot insert explicit value for identity column in table 'PATIENT DONOR' when IDENTITY_INSERT is set to OFF IDENTITY_INSERT设置为OFF时,1:1映射并且无法为表&#39;DivisionParticipant&#39;中的Identity列插入显式值 - 1:1 mapping and Cannot insert explicit value for identity column in table 'DivisionParticipant' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,C#无法为表“出租”中的标识列插入显式值 - C# Cannot insert explicit value for identity column in table “Rentals” when IDENTITY_INSERT is set to OFF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM