【发布时间】: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