简体   繁体   中英

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

I am using 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

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

My Model 2 for inserting related items ids:

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

[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. 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; for it to work. This enables you to insert an ID into the identity column. However, you don't need to specify an ID when inserting a new row into a table with an identity column :)

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

by using List and 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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM