我创建了一个ASP.NET MVC5示例项目。我创建了我的实体,并从中为脚手架控制器进行CRUD操作。我只能使用脚手架代码编辑POD成员。我希望能够添加/删除相关实体。
使用我当前的代码,当我单击“保存”时,没有错误但没有修改相关实体(虽然修改了POD数据)。例如,如果我想从帐户中删除所有玩家,则不会将其删除。我做错了什么?
如何删除/添加相关实体并将这些更改推送到数据库?
以下是更新实体的操作:
var i = 0,
div = $('<div class="base_container">Hi Elia,<br>whats your <b>name</b>?</div>');
function processContent(element){
element.contents().each(function(){
if(this.nodeType == 3){
/* it's safe to process text nodes only */
var content = this.textContent;
content = content.replace(/./g, function(a){ return '<span id="char_' + ++i + '">' + a + '</span>'; })
$(this).replaceWith($(content));
}else{
/* recursively process child nodes */
return processContent($(this));
}
});
}
processContent(div);
console.log(div.html());
以下是模型:
public async Task<ActionResult> Edit([Bind(Include = "Account,Account.AccountModelId,Account.Name,Account.CreatedDate,SelectedPlayers")] AccountViewModel_Form vm){
if (ModelState.IsValid){
if (vm.SelectedPlayers != null){
vm.Account.PlayerModels = db.PlayerModels.Where(p => p.AccountModel.AccountModelId == vm.Account.AccountModelId).ToList();
foreach (var player in vm.Account.PlayerModels){
player.AccountModel = null;
db.Entry(player).State = EntityState.Modified;
}
vm.Account.PlayerModels.Clear();
foreach (var player_id in vm.SelectedPlayers){
var player = db.PlayerModels.Where(p => p.PlayerModelId == player_id).First();
vm.Account.PlayerModels.Add(player);
db.Entry(player).State = EntityState.Modified;
}
}
db.Entry(vm.Account).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(vm);
}
我基本上输了。我无法找到有关如何更新相关数据的任何示例。有人能指出我正确的方向吗?
我来自Symfony(PHP Framework)背景。我觉得这会更容易,但我遇到了问题。
答案 0 :(得分:2)
基本上我错过了Attach
函数,我必须强制加载集合才能使它工作。
我在此处找到了如何附加未附加的实体:Model binding in the controller when form is posted - navigation properties are not loaded automatically
发布数据时,实体未附加到上下文,当您尝试将更改保存到复杂实体时,上下文会变得混乱。
代码有点不同,因为我试图让它在家里工作。但它基本上是相同的模型。
public ActionResult Edit(AccountEditViewModel vm)
{
if (ModelState.IsValid)
{
//I was missing these 2 important lines...
db.Accounts.Attach(vm.Account);
db.Entry(vm.Account).Collection(a => a.Players).Load();
if (vm.SelectedPlayers != null)
{
foreach (var player in vm.Account.Players.ToList())
{
if (vm.SelectedPlayers.Contains(player.Id) == false)
{
player.Account = null;
vm.Account.Players.Remove(player);
db.Entry(player).State = EntityState.Modified;
vm.SelectedPlayers.Remove(player.Id);
}
}
foreach (var player_id in vm.SelectedPlayers)
{
var player = db.Players.Where(p => p.Id == player_id).First();
player.Account = vm.Account;
vm.Account.Players.Add(player);
db.Entry(player).State = EntityState.Modified;
}
}else
{
vm.Account.Players.Clear();
}
db.Entry(vm.Account).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
}