创建一个与现有 parent 相关的新 child 在 dbContext.save() 处创建一个新的 parent
Creatng a new child with a relation to an existing parent creates a new parent at dbContext.save()
我有一个使用代码优先 entity framework 模型创建的一对多 parent child 关系。
下面的代码创建了一个引用现有 parent 的新 child 的结果是我最终得到了一个新的 parent 条目。
我看到一个建议的解决方案是将 parent 附加到上下文或更改它的 EntityState。但是我认为这行不通,因为这两种模型存在于不同的环境中。
不同的上下文对我来说总是很奇怪,但我在某处读到,这样做是很常见的,以保持每个模型的模块化,从而坚持这一点。 (即使他们使用相同的连接字符串等)
所以问题是:
我如何确保 Child 与现有的 parent 相关联,而不是与新创建的相关联?
即使不同的 dbContexts 不是导致问题的原因,这是否明智?
我的控制器代码:
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "Information_Id,Information_Title,Information_LinkText,Information_URLBody")] Information information, int InformationContainer_Id)
{
InformationContainerDBContext dbContainer = new InformationContainerDBContext();
//information.Information_Container = (from p in dbContainer.InformationContainers where p.InformationContainer_Id == InformationContainer_Id select p).ToList()[0];
information.Information_Container = dbContainer.InformationContainers.Single(o => o.InformationContainer_Id == InformationContainer_Id);
if (ModelState.IsValid)
{
dbContainer.Entry(information.Information_Container).State = EntityState.Unchanged;
db.Informations.Add(information);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(information);
}
我的模特:
Parent:
public class InformationContainer
{
[Key]
public int InformationContainer_Id { get; set; }
[Required]
public string InformationContainer_Title { get; set; }
[InverseProperty("Information_Container")]
public List<Information> Informations{ get; set; }
}
public class InformationContainerDBContext : DbContext
{
public InformationContainerDBContext()
: base(ConfigurationManager.ConnectionStrings["DataDBString"].ConnectionString)
{
}
public DbSet<InformationContainer> InformationContainers { get; set; }
}
Child:
public class Information
{
[Key]
public int Information_Id { get; set; }
[Required]
public string Information_Title { get; set; }
[Required]
public string Information_LinkText { get; set; }
[Required]
[AllowHtml]
public string Information_URLBody { get; set; }
public InformationContainer Information_Container { get; set; }
}
public class InformationDBContext : DbContext
{
public InformationDBContext()
: base(ConfigurationManager.ConnectionStrings["DataDBString"].ConnectionString)
{
}
public DbSet<Information> Informations { get; set; }
}
我的看法:
@model eCommSite.Areas.Admin.Models.Information
@{
ViewBag.Title = "Information Pages - Create";
}
<script type="text/javascript" src="~/Scripts/tinymce/tinymce.min.js"></script>
<script>tinymce.init({ selector: 'textarea' });</script>
<h2>Information Pages</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Information_Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Information_Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Information_Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Information_LinkText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Information_LinkText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Information_LinkText, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Information_Container, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<select name="InformationContainer_Id">
<option value="1">Help</option>
<option value="2">Company</option>
<option value="3">Information For Parents</option>
</select>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Information_URLBody, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10" style=" height:500px!important; width: 80%;">
<textarea id=" wysiwyg"
style=" height:350px; width: 500px;"
name="Information_URLBody"></textarea>
</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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
去掉多余的DbContext,只有一个。将此 属性 添加到您的 Information
class,使其成为外键:
public int InformationContainer_Id { get; set; }
您的上下文应如下所示:
public class InformationDBContext : DbContext
{
public InformationDBContext()
: base(ConfigurationManager.ConnectionStrings["DataDBString"].ConnectionString)
{
}
public DbSet<Information> Informations { get; set; }
public DbSet<InformationContainer> InformationContainers { get; set; }
}
因为 InformationContainer_Id
是一个外键,你的控制器代码应该喜欢这个并且它应该工作。
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "Information_Id,Information_Title,Information_LinkText,Information_URLBody")] Information information, int InformationContainer_Id)
{
if (ModelState.IsValid)
{
information.InformationContainer_Id = InformationContainer_Id;
db.Informations.Add(information);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(information);
}
您应该将代码更改为:
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "Information_Id,Information_Title,Information_LinkText,Information_URLBody")] Information information, int InformationContainer_Id)
{
if (ModelState.IsValid)
{
InformationContainerDBContext dbContainer = new InformationContainerDBContext();
var infContainer = dbContainer.InformationContainers.Single(o => o.InformationContainer_Id == InformationContainer_Id);
infContainer.Informations.Add(information);
dbContainer.SaveChanges();
return RedirectToAction("Index");
}
return View(information);
}
如果您将导航 属性 添加到已存在的集合 属性,它也会被添加到数据库。
这里发生了一些事情:
首先,拥有多个 DbContext 很疯狂,通过一些工作我将它们全部合并。
(如果您正在阅读这篇文章 post... 只需要维护一个 DbContext 是一个巨大的问题,无论您对可能涉及的工作有多恐惧,我都强烈建议合并,尤其是如果您就像我一样,由于缺乏经验而只有多个上下文。)
其次,我添加了对来自另一个上下文的实体的引用以及对实体的引用而不是它们的 ID,这在调用保存更改时创建了新实体
我有一个使用代码优先 entity framework 模型创建的一对多 parent child 关系。
下面的代码创建了一个引用现有 parent 的新 child 的结果是我最终得到了一个新的 parent 条目。
我看到一个建议的解决方案是将 parent 附加到上下文或更改它的 EntityState。但是我认为这行不通,因为这两种模型存在于不同的环境中。
不同的上下文对我来说总是很奇怪,但我在某处读到,这样做是很常见的,以保持每个模型的模块化,从而坚持这一点。 (即使他们使用相同的连接字符串等)
所以问题是: 我如何确保 Child 与现有的 parent 相关联,而不是与新创建的相关联?
即使不同的 dbContexts 不是导致问题的原因,这是否明智?
我的控制器代码:
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "Information_Id,Information_Title,Information_LinkText,Information_URLBody")] Information information, int InformationContainer_Id)
{
InformationContainerDBContext dbContainer = new InformationContainerDBContext();
//information.Information_Container = (from p in dbContainer.InformationContainers where p.InformationContainer_Id == InformationContainer_Id select p).ToList()[0];
information.Information_Container = dbContainer.InformationContainers.Single(o => o.InformationContainer_Id == InformationContainer_Id);
if (ModelState.IsValid)
{
dbContainer.Entry(information.Information_Container).State = EntityState.Unchanged;
db.Informations.Add(information);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(information);
}
我的模特:
Parent:
public class InformationContainer
{
[Key]
public int InformationContainer_Id { get; set; }
[Required]
public string InformationContainer_Title { get; set; }
[InverseProperty("Information_Container")]
public List<Information> Informations{ get; set; }
}
public class InformationContainerDBContext : DbContext
{
public InformationContainerDBContext()
: base(ConfigurationManager.ConnectionStrings["DataDBString"].ConnectionString)
{
}
public DbSet<InformationContainer> InformationContainers { get; set; }
}
Child:
public class Information
{
[Key]
public int Information_Id { get; set; }
[Required]
public string Information_Title { get; set; }
[Required]
public string Information_LinkText { get; set; }
[Required]
[AllowHtml]
public string Information_URLBody { get; set; }
public InformationContainer Information_Container { get; set; }
}
public class InformationDBContext : DbContext
{
public InformationDBContext()
: base(ConfigurationManager.ConnectionStrings["DataDBString"].ConnectionString)
{
}
public DbSet<Information> Informations { get; set; }
}
我的看法:
@model eCommSite.Areas.Admin.Models.Information
@{
ViewBag.Title = "Information Pages - Create";
}
<script type="text/javascript" src="~/Scripts/tinymce/tinymce.min.js"></script>
<script>tinymce.init({ selector: 'textarea' });</script>
<h2>Information Pages</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Information_Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Information_Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Information_Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Information_LinkText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Information_LinkText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Information_LinkText, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Information_Container, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<select name="InformationContainer_Id">
<option value="1">Help</option>
<option value="2">Company</option>
<option value="3">Information For Parents</option>
</select>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Information_URLBody, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10" style=" height:500px!important; width: 80%;">
<textarea id=" wysiwyg"
style=" height:350px; width: 500px;"
name="Information_URLBody"></textarea>
</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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
去掉多余的DbContext,只有一个。将此 属性 添加到您的 Information
class,使其成为外键:
public int InformationContainer_Id { get; set; }
您的上下文应如下所示:
public class InformationDBContext : DbContext
{
public InformationDBContext()
: base(ConfigurationManager.ConnectionStrings["DataDBString"].ConnectionString)
{
}
public DbSet<Information> Informations { get; set; }
public DbSet<InformationContainer> InformationContainers { get; set; }
}
因为 InformationContainer_Id
是一个外键,你的控制器代码应该喜欢这个并且它应该工作。
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "Information_Id,Information_Title,Information_LinkText,Information_URLBody")] Information information, int InformationContainer_Id)
{
if (ModelState.IsValid)
{
information.InformationContainer_Id = InformationContainer_Id;
db.Informations.Add(information);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(information);
}
您应该将代码更改为:
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "Information_Id,Information_Title,Information_LinkText,Information_URLBody")] Information information, int InformationContainer_Id)
{
if (ModelState.IsValid)
{
InformationContainerDBContext dbContainer = new InformationContainerDBContext();
var infContainer = dbContainer.InformationContainers.Single(o => o.InformationContainer_Id == InformationContainer_Id);
infContainer.Informations.Add(information);
dbContainer.SaveChanges();
return RedirectToAction("Index");
}
return View(information);
}
如果您将导航 属性 添加到已存在的集合 属性,它也会被添加到数据库。
这里发生了一些事情:
首先,拥有多个 DbContext 很疯狂,通过一些工作我将它们全部合并。
(如果您正在阅读这篇文章 post... 只需要维护一个 DbContext 是一个巨大的问题,无论您对可能涉及的工作有多恐惧,我都强烈建议合并,尤其是如果您就像我一样,由于缺乏经验而只有多个上下文。)
其次,我添加了对来自另一个上下文的实体的引用以及对实体的引用而不是它们的 ID,这在调用保存更改时创建了新实体