我正在努力掌握EF4 CTP5。我有两个类具有多对多关系:Member和MemberGroup。CTP5代码首先生成了两个表(Members和MemberGroups),还有第三个名为MemberGroupMembers的表,它有两列(MemberGroupId和MemberId)。到目前为止,一切都如我所期望的那样。我已经为数据库添加了一些Members和MemberGroups。问题是,我找不到如何将一个或多个MemberGroup分配给某个成员,这将导致在MemberGroupMembers表中为分配给该成员的每个MemberGroup插入一行。
public class Member
{
public int Id { get; set; }
public Guid SecureId { get; set; }
public DateTime JoinedOn { get; set; }
public virtual ICollection<MemberGroup> MemberGroups { get; set; }
}
public class MemberGroup
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
public class CTP5testContext : DbContext
{
public CTP5testContext() : base("CTP5test") { }
public DbSet<Member> Members { get; set; }
public DbSet<MemberGroup> MemberGroups { get; set; }
}
public class CTP5testContextInitializer : DropCreateDatabaseIfModelChanges<CTP5testContext>
{
protected override void Seed(CTP5testContext context)
{
new List<Member>
{
new Member
{
Id = 1,
SecureId = Guid.NewGuid(),
JoinedOn = DateTime.Now
}
,
new Member
{
Id = 2,
SecureId = Guid.NewGuid(),
JoinedOn = DateTime.Now
}
}.ForEach(m => context.Members.Add(m));
var memberGroup = new MemberGroup()
{
Id = 1,
Name = "MemberGroup 1",
CreatedOn = DateTime.Now
};
context.MemberGroups.Add(memberGroup);
// How can I assign Member 1 to MemberGroup 1 ?????
context.SaveChanges();
}
}
我希望我在这里要做的事情很清楚,有人能给我一个如何实现这一目标的例子。
Regards, Erwin