John L.
John L.

Reputation: 1953

Adding To Association Table Without Loading

I have three tables: A, B, and an association table AB. Since Entity Framework does not create a separate entity for the association table, only entities A and B are created.

Now, I want to add Bs to the A entity but I do not want to load all these B entities from the database since I know the Id's of the B entities I want to add to A. I tried to do the following:

A.Bs.Add(
    new B(){
        Id = 100
    }
);

The problem is that when there is no B entity with Id of 100, instead of throwing an exception due to the foreign key constraint, EF creates a new B entity with Id of 100 and then adds this to the association table.

How can I prevent the creation of a new B?

Upvotes: 0

Views: 105

Answers (1)

John L.
John L.

Reputation: 1953

It looks like creating the B object outside the Add operation and either attaching it to the context or marking its state as "Unchanged" works as required.

var b = new B(){
    Id = 100
};

context.B.Attach(b);
//OR
context.Entry(b).State = EntityState.Unchanged;

A.Bs.Add(b);

Upvotes: 2

Related Questions