Entity Framework adding record into many to many mapping table

.net c# entity-framework many-to-many

Accepted Answer

Flying somewhat blind because you omitted what attributesentity has. However, you need to have a property for the connection to.CustomerGroups . Simply include the organizations you want to be associated to in that property. For instance, this would associate the entity with the group "foo bar" and give the group a new name.

using (var context = DataObjectFactory.CreateContext())
{
    entity.CustomerGroups = new List<CustomerGroup> { GroupName = "Foo bar" };
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}

EF will automatically put a record into the relationship if it is set up properly.CustomerGroups likewise add a relationship to theCustomerInGroups table.

EDIT:

Attempting to add an already existentCustomerGroup to a fresh client. You should purchase theCustomerGroup you should add it to the Customer object you are inserting after removing it from the database.

using (var context = DataObjectFactory.CreateContext())
{
    var customerGroups = context.CustomerGroups.Where(...).ToList(); // get your CustomerGroup object(s) here, and ensure it's enumerated with ToList()
    entity.CustomerGroups = customerGroups;
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}
8
3/7/2013 3:15:53 PM

Popular Answer

Assuming that the CustomerGroup object exposes an ICollection and that you are attempting to assign a existing customer to an existing group, take the following actions:

(var context = DataObjectFactory.CreateContext())
{
    context.Customers.Add(entity);
    var group = context.CustomerGroups.Find(2); // or however you retrieve the existing group
    group.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id
}

The Entity Framework Code First (DbContext) method for locating by Id is the Find() method. However, I can't immediately recall the "correct" ObjectContext method of doing it. Another option is Single(g => g.Id == 2).

We'd prefer it if you could give us a clearer sense of how your entities are mapped so we can understand how you're connecting them.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow