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

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

问题描述

此代码适用于:

  var c = cboCustomer.SelectedItem作为客户; 
var t = cboTrailer.SelectedItem作为预告片;
using(var db = new 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个相关的客户。我希望使用客户。



我正在使用EF 5.0模型,这里是edmx图的一部分:





更新1(根据Boomer的建议):

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

返回:



该对象无法被删除,因为它在ObjectStateManager中没有找到。

解决方案

错误是因为客户在这种关系中被要求是明显的。这就像你在数据库中插入一个Trailer记录而不指定CustomerID,你可以在SQL中这么做吗?



一个更好的方法是删除该对象的ID例如。在这种情况下,您不必在删除之前附加 t

  using(var db = new 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天全站免登陆