Willy
Willy

Reputation: 10660

EF 4.1 Code first - Many to Many - State unchanged

I have a many to many relationship, see my scenario explained here before continuing reading: EF 4.1 Code First: Many to Many

Ok, now I can add the entries to the respective tables by doing the solution proposed by Slauma (see below) but I do not want to insert any entry to one of the tables (table B) as it has fixed entries (readonly). so how to achieve it? I mark it as unchanged but it is not working.

I do the following:

A a = new A() { PropertyA1 = something_1,
            PropertyA2 = something_2,
            PropertyA3 = something_3 };
a.Bs = new List<B>();

foreach (.....)
{
  B b = new B() { ..... }
  a.Bs.Add(b);
}

context.A.Add(a);

// Below loop is not working
foreach (var entry in context.ChangeTracker.Entries()
        .Where(e => e.State == EntityState.Added && e.Entity is SomeEntity))
{
        entry.State = EntityState.Unchanged;
}

context.SaveChanges();

If I remove previous foreach, information is added correctly to tables A and link table C, but also in B and I do no want info to be added in B.

Any ideas?

Upvotes: 0

Views: 96

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109252

Where you do

B b = new B() { ..... }

you must in stead fetch an existing B from the database and add that to a.Bs.

Upvotes: 1

Related Questions