【发布时间】:2017-08-31 05:12:19
【问题描述】:
这是我在这个网站上的第一个问题。我在 ASP.Net Web 应用程序中自学 MVC 和实体框架。我有一系列相关实体,当我调用 context.saveChanges() 时,已删除的相关数据项不会被删除。
我的实体 我有一个可以有 0 到多个别名的项目实体。这是数据库第一个项目,其中大部分代码行都是自动生成的。
public Class Item
{
public int Id{get;set};
public string Name {get;set;}
public virtual ICollection<AliasClass> AssociatedAliases {get;set;}
}
public Class AliasClass
{
public int Id {get;set;}
public int ItemId {get;set;}
public string AliasName {get;set;}
public virtual Item RelatedItem {get;set;}
}
好的,我们已经完成了自动生成的内容。我的回发操作接受回发视图模型。我正在实施存储库模式。我的 Item Repo 有更新功能。
[HttpPost]
public ActionResult Edit (Models.EditViewPostBack MyPostBackModel)
{
If (!ModelState.isValid){
... rebuild and copy // this part works. Skipping over it
}
// this may be a key line of my issue
MyPostBackModel.Item.Alias = MyPostBackModel.myAliases;
ItemRepo.Update(MyPostBackModel.Item);
return RedirectToAction("Index","Home");
}
这里是 Models.EditViewPostBack。新的关联列表作为数组传回。新关联的 id 为 0。在更新时,它将被分配一个真实的 Id。
public class EditViewPostBack{
Item myItem {get; set;}
AliasClass[] myAliases {get;set;}
}
现在,终于到了项目的核心和我真正的问题。这是 ItemRepo 中应该更新更改的方法。
public void Update (Item myItem)
{
// myItem.AssociatedAliases contains only the wanted associations.
// It doesn't have the to-be deleted items.
// new items have an id of 0
// defined in class constructor.
context.Item.Attach(myItem);
context.Entry(Item).State = EntityState.Modified;
foreach(var name in myItem.AssociatedAliases){
// finds the modified local version of the item. doesn't connect
// to the database to location info.
if(name.id > 0)
{
var moded = context.AliasClass.find(name.Id);
context.Entry(moded).State = EntityState.Modified;
}
else
{
// it is brand new
context.Item.Add(name)
}
}
//
// Once the alias is not attached to it's item it has to go
// How to handle deletes goes here
//
context.SaveChanges();
}
因为实体状态没有被标记为已删除,所以关联仍然存在,并且该项目看起来就像我从未删除它一样。我已经尝试了几件事。
如果我使用 context.Alias.linqFunction() 加载或搜索原始项目,则由于 id 匹配,整个列表将与 myItem 参数重新关联。
// invoking the following line causes Item.Alias to fully re-associate.
// I lose the list passed to the function
context.AliasClass.Where(x=>x.ItemId == myItem.Id)
我目前无法加载别名,因为这将是到我不删除项目的数据库的往返。
我认为我需要一种删除方法,除非 Id 与仍然连接的列表匹配。但是 remove 需要一个要删除的项目的实例。
如何从我的数据库中删除这些关联的别名?
【问题讨论】:
标签: c# asp.net-mvc entity-framework