views:

452

answers:

4

I have just started a new project using a Linq to Sql model and I'm implementing our first many to many relationship. I have found this blog that gives great info on how implement this:

http://blogs.msdn.com/mitsu/archive/2008/03/19/how-to-implement-a-many-to-many-relationship-using-linq-to-sql-part-ii-add-remove-support.aspx

When I try to add some child objects in and then remove one before saving I get an error,

System.InvalidOperationException: Cannot remove an entity that has not been attached.

Any ideas? Someone has already commented on this to the author of the blog, but there has been no response.

Much appreciated!

A: 

You are calling DeleteOnSubmit, on an entity that has not been sucked into the DataContext.

To check for this (in a rather hacky way), do the following:

var e = some_entity;

var cs = dc.GetChangeSet();

if (cs.Inserts.Any( x => x == e))
{
  dc.SomeTable.DeleteOnSubmit(e);
}

dc.SubmitChanges();
leppie
A: 

If you have created a new entity then trying to remove it you need to make sure you Attach it to the entity instance beforehand i.e.

Customer c = new Customer();
c.CustomerID = "12345";
db.Customers.Attach(c);
db.Customers.Remove(c);
db.SubmitChanges();
James
I think you are few beta's behind :O
leppie
Could possibly be haven't used Linq in a while!
James
A: 

I suspect that's why the author mentions that this particular post is working 'in memory' and not with linq to sql. Another approach would be to modify the onAdd event to Insert the added object into the context, that should at least alleviate the error you are seeing.

Lazarus
A: 

Take a look at the way PLINQO handles many to many relationships. There is a List of each entity that relates to another entity through a many to many relationship. You can add and remove without receiving the error you mention here.

Shannon Davidson