我正试图掌握EF4 CTP5。我有两个具有多对多关系的类:Member和MemberGroup。 CTP5 Code First生成了两个表(成员和成员组),还有第三个名为MemberGroupMembers的列有两列(MemberGroupId和MemberId)到目前为止,所有内容都是我期望的那样。我已经使用一些成员和成员组播种了数据库。问题是我找不到如何将一个或多个MemberGroup分配给一个Member,这会导致在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();
}
}
我希望我在这里做的很清楚,有人可以给我一个如何实现这个目标的例子。
此致 欧文
答案 0 :(得分:0)
您必须使用POCO课程中定义的集合。因此,如果您想将member1分配给memberGroup,您只需调用:
memberGroup.Members.Add(member1);