如何在不访问对象上下文的情况下删除Entity Framework中的关联对象 [英] How to delete an associated object in Entity Framework without having access to the object context

查看:98
本文介绍了如何在不访问对象上下文的情况下删除Entity Framework中的关联对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有两个模型,即站点和链接,其中一个站点具有许多链接,如何从不能访问对象上下文的Site方法中删除一个链接?

Having two models, Site and Link, where a site has many links, how do I delete a link from inside a method of Site, which doesn't have access to the object context?

我尝试过类似的操作:

public void DeleteFirstLink() {
    var link = LinkSet.First();
    LinkSet.Remove(link);
}

似乎并不是真正删除链接,而是破坏了关联。由于存在数据库约束,因此会引发此错误:

but it seems that is not really deleting the link, but breaking the association. Since there's a database constraints it throws this error:


正在从AssociationSet'Sites_have_Links'中添加或删除关系。受基数约束,还必须添加或删除相应的链接。

A relationship is being added or deleted from an AssociationSet 'Sites_have_Links'. With cardinality constraints, a corresponding 'Links' must also be added or deleted.

实际上如何从数据库中删除链接?

How do I actually delete the link from the database?

推荐答案

假定在调用DeleteFirstLink()方法时ObjectContext不活跃,则可以通过旋转一个方法中的上下文,附加Site实体,然后删除链接:

Assuming that your ObjectContext is not alive when you call the DeleteFirstLink() method, you can make it work by spinning up a context inside the method, attaching the Site entity, and then deleting the link:

public void DeleteFirstLink()
{
  using (ProjectEntities db = new ProjectEntities())
  {
    db.AttachTo("[your site EntitySet name - SiteSet?]", this);
    var link = LinkSet.First();
    db.DeleteObject(link);
    LinkSet.Remove(link);
    db.SaveChanges();
  }
}

这篇关于如何在不访问对象上下文的情况下删除Entity Framework中的关联对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆