0
我正試圖與EF4 CTP5進行交涉。我有兩個具有多對多關係的類:Member和MemberGroup。 CTP5代碼首先生成兩個表(Member和MemberGroups),還有第三個名爲MemberGroupMembers的有兩列(MemberGroupId和MemberId)。到目前爲止,所有事情都像我期待的那樣。我已經與一些會員和會員組一起播種了數據庫。問題是我無法找到如何將一個或多個MemberGroups分配給成員,這會導致爲該成員分配給的每個MemberGroup在MemberGroupMembers表中插入一行。在多對多的關係中填充鏈接表
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();
}
}
我希望它是清楚,我想在這裏做,並且有人可以給我如何做到這一點的例子。
的問候, 歐文
Hi Ladislav,感謝您的快速響應。我在我的類定義中將ICollection更改爲Collection。我在`memberGroup.Members.Add(member1)'上得到一個NullReferenceException;` – enstam 2011-02-17 09:37:31