我为什么不能删除与刚刚.DeleteObject(O)的实体? [英] Why can I not delete an entity with just .DeleteObject(o)?

查看:806
本文介绍了我为什么不能删除与刚刚.DeleteObject(O)的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码的工作:

 变种C = cboCustomer.SelectedItem的客户; 
变种T = cboTrailer.SelectedItem的拖车;
使用(VAR DB =新CAPSContainer())
{
db.Attach(C);
db.Attach(T);
c.Trailers.Remove(T);
db.DeleteObject(T);
db.SaveChanges();
}



但我不明白为什么我不能做的:

  db.Attach(T); 
db.DeleteObject(T);
db.SaveChanges();

如果我尝试,我得到:



在'CAPSContainer.Trailers实体参加CustomerTrailer的关系。 0相关的客户被发现了。 1客户有望



我使用EF 5.0型号第一,这里是EDMX图的一部分:





< 。p>我发现很难理解为什么,请大家帮忙



更新1(正如布玛建议):

 使用(VAR DB =新CAPSContainer())
{
db.Attach(C);
//db.Attach(t);
//c.Trailers.Remove(t);
db.DeleteObject(T);
db.SaveChanges();
}



返回:



的对象不能因为它没有在ObjectStateManager中删除。


解决方案

该错误是由于顾客明显是必需的这种关系。它就像你正在插入数据库中的一个花絮记录而不指定客户ID,就可以做到这一点在SQL?



有一个更好的方法将是删除由ID的对象例如。在这种情况下,你没有之前删除它附加 T

 使用(VAR DB =新CAPSContainer())
{
db.DeleteObject(db.Trailers.Where(p => p.ID == t.ID));
db.SaveChanges();
}

或加载,当所有的拖车(下拉内),你也应该获得客户与它连接的任何其他强制性的实体。


This code works :

var c = cboCustomer.SelectedItem as Customer;
var t = cboTrailer.SelectedItem as Trailer;
using (var db = new CAPSContainer())
{
   db.Attach(c);
   db.Attach(t); 
   c.Trailers.Remove(t);
   db.DeleteObject(t);
   db.SaveChanges();
}

But I dont understand why I cannot just do :

db.Attach(t);
db.DeleteObject(t);
db.SaveChanges();

If I try that I get :

Entities in 'CAPSContainer.Trailers' participate in the 'CustomerTrailer' relationship. 0 related 'Customer' were found. 1 'Customer' is expected.

I am using EF 5.0 Model first and here is part of the edmx diagram :

I am finding it hard to understand why, please help.

UPDATE 1 (As suggested by Boomer):

            using (var db = new CAPSContainer())
            {
                db.Attach(c);
                //db.Attach(t);
                //c.Trailers.Remove(t);
                db.DeleteObject(t);
                db.SaveChanges();
            }

Returns :

The object cannot be deleted because it was not found in the ObjectStateManager.

解决方案

The error is obvious since the Customer is required in this relation. It is like you are inserting a Trailer record in the database without specifying the CustomerID, can you do that in SQL?

A better approach will be to delete that object by ID for example. In that case, you don't have to attach t before deleting it:

using (var db = new CAPSContainer())
{   
    db.DeleteObject(db.Trailers.Where(p => p.ID == t.ID));
    db.SaveChanges();
}

Or when loading all the Trailers (within the dropdown), you should also get the Customer with it and any other mandatory entity attached.

这篇关于我为什么不能删除与刚刚.DeleteObject(O)的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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