Reputation: 137
I am using Visual Studio 2008 with .NET Framework 3.5.
I am trying to do what I had thought would be a simple deletion of some rows using LINQ to entities.
I have a simple SQL Server database back end and I am using Data Entity Framework to access it. I have done nothing to the default behavior created in the EDMX.
I am attempting the following code:
myDB.Dispose();
myDB = new EChODatabaseConnection();
//get our equipment list of requested equipment
var OldEquip = from u in myDB.dbEquipmentRequestedSet
where u.iRequestID == requestID
select u;
myDB.DeleteObject(OldEquip);
myDB.SaveChanges();
It gets to the db.DeleteObject(OldEquip) and generates the following error:
"The object cannot be deleted because it was not found in the ObjectStateManager."
I have verified that there is something in OldEquip before the line of code is executed.
I added the first two lines of code(Dispose and new) on the off chance there was an issue with previous code.
EDIT The dbEquipmentRequestedSet looks like this:
iRequestID (in db an int)
sCode (in db a varchar(50))
SCodePrefix (in db a varchar(10))
I use a composite primary key based upon iRequestID and sCode.
EDIT2 To clarify, in almost all cases, the OldEquip query will result in more than one result.
From the answers so far, it appears that I will have to manually go through each entry to delete.
Is there a more elegant solution? Maybe by using a stored procedure?
Upvotes: 1
Views: 287
Reputation: 18237
I have some extension methods I use to delete multiple objects at once if you want to use them:
public static void DeleteAll(this ObjectContext context, IEnumerable<object> collection)
{
foreach (var item in collection.ToList())
{
context.DeleteObject(item);
}
}
public static void DeleteAll<TEntity>(this ObjectSet<TEntity> context, IEnumerable<TEntity> collection) where TEntity : class
{
foreach (var item in collection.ToList())
{
context.DeleteObject(item);
}
}
Upvotes: 0
Reputation: 100587
Sounds like you want to delete multiples. Try this:
var OldEquip = (from u in myDB.dbEquipmentRequestedSet
where u.iRequestID == requestID
select u)
.ToList();
foreach(var item in OldEquip)
{
myDB.DeleteObject(item);
}
The likely cause if that DeleteObject
accepts an object, which should be an entity that is contained in the ObjectStateManager.Your code currently passed it an ObjectQuery<T>
which isn't contained in the ObjectStateManager.
More at this MSDN forum post.
Upvotes: 1
Reputation: 48486
OldEquip
in this case is of type IQueryable. You can only delete actual entities, so you will have to modify the LINQ statement to something like:
var OldEquip = (from u in myDB.dbEquipmentRequestedSet
where u.iRequestID == requestID
select u).First();
or if the query returns multiple values, loop through all the results in the IQueryable using foreach
and delete all items separately.
Upvotes: 0