ICollections 方法:更新:
如果我理解正确你有多对多关系(组有很多用户,用户可以在很多组中),在这种情况下代码应该是这样的:
public class RelationExampleContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<SubGroup> SubGroups { get; set; }
}
public class User
{
[Key]
public int ID { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public ICollection<SubGroup> SubGroups { get; set; }
}
public class SubGroup
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public ICollection<User> Users { get; set; }
}
将用户添加到组示例:
var db = new RelationExampleContext();
var subGroups = new List<SubGroup>
{
new SubGroup() {Name = "Subgroup1"},
new SubGroup() {Name = "Subgroup2"}
};
var users = new List<User>
{
new User()
{
Forename = "Forename1",
Surname = "Surname1",
SubGroups = new List<SubGroup>
{
subGroups.First(),
subGroups.Last()
}
},
new User()
{
Forename = "Forename2",
Surname = "Surname2",
SubGroups = new List<SubGroup>
{
subGroups.First()
}
}
};
foreach (var subGroup in subGroups)
{
db.SubGroups.Add(subGroup);
}
foreach (var user in users)
{
db.Users.Add(user);
}
db.SaveChanges();