如何删除在实体框架的asociated对象,而无需访问对象上下文 [英] How to delete an asociated object in Entity Framework without having access to the object context

查看:145
本文介绍了如何删除在实体框架的asociated对象,而无需访问对象上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种型号,网站和链接,其中一个网站有很多的链接,我该如何删除网站的一种方法,它没有访问对象上下文中的链接?

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:

一个关系被添加或从AssociationSetSites_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是不是还活着,你可以把它通过旋转起来的方法中一个背景下,安装的现场工作实体,然后删除链接:

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();
  }
}

这篇关于如何删除在实体框架的asociated对象,而无需访问对象上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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