Carlos G.
Carlos G.

Reputation: 4634

Remove Entity from DataContext so that its not inserted (Linq-to-SQL)

In my application I have 2 entities that are defined as:

public class A {
       public B ClassB { get; set; }
       // Bunch of code
}

public class B {
       // Bunch of code
}

When I create a new instance of class A, assign it a new instance of B and insert A into the DataContext, the instance of B is also inserted into the DataContext. My problem appears when I want the DataContext not no insert that entity into the database. I have not found any way to eliminate that entity from the DataContext so that it is not inserted. I've tried:

DataContext.A.DeleteOnSubmit(InstanceOfB);

to no avail.

Does anyone has an idea what I'm doing wrong??

Thanks

The

Upvotes: 0

Views: 905

Answers (1)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

This is by design - & is usually a desirable outcome!

Linq-to-SQL inserts child objects to preserve relational integrity. If you can turn that off somehow, the next obvious solution is to remove the relationship. This is not an ideal suggestion but it will work.

A.B = null;

Now A does not have a ClassB object, and hence the Insert statement will not insert your B.

Upvotes: 2

Related Questions