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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…