使用多对多关系创建相关实体的正确方法是什么

时间:2015-11-07 09:08:54

标签: asp.net-mvc entity-framework many-to-many

我是Entity Framework的新手。只是想知道用多对多关系创建相关实体的正确方法是什么。我总是在调试时遇到此错误:" 对象引用未设置为对象的实例"。

以下面的例子为例:

以下是数据模型,俱乐部可以有多个会员,一个会员可以加入多个俱乐部

public class Club       
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Member> Member { get; set; }
}
public class Member
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Club> Club { get; set; }
}

我尝试创建一个新的俱乐部并为其添加一个新成员(这两个对象都不是数据库中的现有数据):

Member member = new Member();
Club club=new Club();
member.Name = "Amy";
club.Name="NBA Fans";
member.Club.Add(club); //Error: Object reference not set to an instance of an object
db.Member.Add(member);
db.SaveChanges();

有人可以提供正确的方法吗?

非常感谢

1 个答案:

答案 0 :(得分:0)

你可以试试这个

修改:

请点击此链接Saving Many to Many relationship data on MVC Create view

public class Club       
{
    public int ClubId { get; set; }
    public string Name { get; set; }
}
public class Member
{
    public int MemberId { get; set; }
    public string Name { get; set; }
}

编辑课程:

public class ClubMembers
{
    public int ClubMember { get; set; }
    public List<Member> Member { get; set; }
    public List<Club> Club { get; set; }
}

List<Club> clubList=new List<Club>();
Club club = new Club();
club.ClubId=1;
club.Name="Club1";
clubList.Add(club);

List<Member> memberList = new List<Member>();
Member member = new Member();
member.MemberId = 1;
member.Name = "Govinda";
memberList.Add(member);

ClubMembers clubMembers=new ClubMembers();
clubMembers.Club = clubList;
clubMembers.Member=memberList;

foreach (var item in clubMembers.Club)
{
    //do code for club entity
}

foreach (var item in clubMembers.Member)
{
    //do code for member entity
}