ASP.NET MVC3 EF代码优先 - 多对多关系

时间:2012-01-23 09:01:15

标签: c# asp.net-mvc-3 many-to-many ef-code-first

我正试图在我的MVC项目中首先使用EF代码创建多对多关系。我有一个场景,我有一个服务,可以有许多类别,可能有许多子类别。这一点似乎工作正常。

每个服务,类别和子类别也可以有许多与之关联的HelpDeskMembers。这是我在创建关联时遇到问题的地方。通过下面的课程,我希望EF能够创建Service_HelpDeskMembers,Category_HelpDeskMembers和Subcategory_HelpDeskMembers表。请有人能指导我朝正确的方向发展吗?

P.S。在导航属性中,我没有使用虚拟,因为我使用AJAX和JSON在Service / Category / Subcategory之间创建级联下拉列表,并且使用'virtual',我收到循环引用错误。

这是我的课程。

public class Service
{
    [Key]
    public int ServiceID { get; set; }

    public string Title { get; set; }
    public DateTime CreatedDate { get; set; }
    public HelpDeskMember CreatedBy { get; set; }
    public DateTime? DeletedDate { get; set; }
    public HelpDeskMember DeletedBy { get; set; }

    public ICollection<Category> Categories { get; set; }
    public ICollection<HelpDeskMember> LinesOfSupport { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    [ForeignKey("Service")]
    public int ServiceID { get; set; }

    public string Title { get; set; }
    public DateTime CreatedDate { get; set; }
    public HelpDeskMember CreatedBy { get; set; }
    public DateTime? DeletedDate { get; set; }
    public HelpDeskMember DeletedBy { get; set; }

    public Service Service { get; set; }
    public ICollection<Subcategory> Subcategories { get; set; }
    public ICollection<HelpDeskMember> LinesOfSupport { get; set; }
}

public class Subcategory
{
    [Key]
    public int SubcategoryID { get; set; }
    [ForeignKey("Category")]
    public int CategoryID { get; set; }

    public string Title { get; set; }
    public DateTime CreatedDate { get; set; }
    public HelpDeskMember CreatedBy { get; set; }
    public DateTime? DeletedDate { get; set; }
    public HelpDeskMember DeletedBy { get; set; }

    public Category Category { get; set; }
    public ICollection<HelpDeskMember> LinesOfSupport { get; set; }       
}

public class HelpDeskMember
{
    public int HelpDeskMemberID { get; set; }
    public string Name { get; set; }
    public bool Admin { get; set; }
    public bool Available { get; set; }
    public DateTime? CreatedDate { get; set; }
    public DateTime? LastLogin { get; set; }
    public DateTime? DeletedDate { get; set; }
    public DateTime? DeletedBy { get; set; }

    public ICollection<Service> Services { get; set; }
    public ICollection<Category> Categories { get; set; }
    public ICollection<Subcategory> Subcategories { get; set; }
}

提前致谢。

1 个答案:

答案 0 :(得分:3)

这里的技巧是使用模型构建器来创建多对多链接,然后它将在db中运行(带有链接表)

请查看此文章,详细了解如何执行多对多http://blogs.microsoft.co.il/blogs/gilf/archive/2011/08/01/creating-a-many-to-many-mapping-using-code-first.aspx