I have 3 tables,
1) Customer (Id, Name, bla bla)
2) CustomerGroups (GroupId, GroupName)
3) CustomerInGroups (CustomerId, GroupId)
using (var context = DataObjectFactory.CreateContext())
{
context.Customers.Add(entity);
context.SaveChanges();
return entity.Id;
}
How do I add a record into CustomerInGroups? EntityFramework doesn't generate entities for such many-to-many mapping tables
Edit:
Both the Id columns in Customer and CustomerGroups are set to auto increment.
So in my CustomersGroup table, I have
Id Name
----------------------------
1 Normal
2 VIP
I tried doing this as one of the posters suggested:
entity.CustomerGroups = new List<CustomerGroup>
{
new CustomerGroup {Id = 2 }
};
context.Customers.Add(entity);
context.SaveChanges();
return entity.Id;
However, when I did this, instead of creating a record in the mapping table like this:
CustomerId GroupId
----------------------------
1 2
What I got was
CustomerInGroups
CustomerId GroupId
----------------------------
1 3
CustomerGroups
Id Name
----------------------------
1 Normal
2 VIP
3 NULL
It actually created another entry in my CustomerGroups table, which is not what I want
Flying a little blind since you didn't include what properties entity
has. But you should have a property for the relationship to CustomerGroups
. Just set that property with the groups you want to be related to. For example, this would create a new Group name "foo bar" and relate the entity to that group.
using (var context = DataObjectFactory.CreateContext())
{
entity.CustomerGroups = new List<CustomerGroup> { GroupName = "Foo bar" };
context.Customers.Add(entity);
context.SaveChanges();
return entity.Id;
}
If the relationship is setup correctly, EF will automatically insert a record into CustomerGroups
and insert a relationship into the CustomerInGroups
table.
EDIT:
If you're trying to add an existing CustomerGroup
to a new Customer. You'll want to get the CustomerGroup
from the database first, then add it to the Customer entity you're inserting.
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;
}