Joper
Joper

Reputation: 8209

EF 4.0 Insert entity with many-to-many relationship

I am using POCO entities.

A have many to many relations like that:

DB tables:

Car-CarTrackType-TrackType

Model Entities:

Car - Track

I want to insert cars witch belongs different TrackTypes. Is it possible with EF 4.0 to create such query to process insert like that in one go?

What i mean:

I have such values in TrackType table:

TrackType
1 Good
2 Bad
3 Weat

I want my insert to produce result like that:

Car(Table)         CarTrackType(Table)
1 BMW              1  2 (CarId, TrackTypeId)          
2 Volvo            1  1
                   1  3
                   2  2
                   2  3 

Any suggestions?

Upvotes: 1

Views: 176

Answers (2)

Nilesh Hirapra
Nilesh Hirapra

Reputation: 51

See one more example of achiving same thing. When new object added to Context, state of all object in object tree changes to Added and hence EF tries to save all such objects as new record.

Upvotes: 0

Slauma
Slauma

Reputation: 177133

You can try something like this:

using (var context = new MyContext())
{
    var truckTypeGood = new TruckType { ID = 1 };
    var truckTypeBad = new TruckType { ID = 2 };
    var truckTypeWeat = new TruckType { ID = 3 };

    context.TruckTypes.Attach(truckTypeGood);
    context.TruckTypes.Attach(truckTypeBad);
    context.TruckTypes.Attach(truckTypeWeat);

    var bmw = new Car {
        Name = "BMW",
        TruckTypes = new List<TruckType>()
        {
            truckTypeGood,
            truckTypeBad,
            truckTypeWeat
        } };

    context.Cars.AddObject(bmw);

    var volvo = new Car {
        Name = "Volvo",
        TruckTypes = new List<TruckType>()
        {
            truckTypeBad,
            truckTypeWeat
        } };

    context.Cars.AddObject(volvo);

    context.SaveChanges();
}

EF manages the many-to-many join table internally so you don't have to care about the records in this table. Instead of attaching the truck types to the context alternatively you can also fetch them from the DB in a query.

Upvotes: 1

Related Questions