获取Entity框架中多对多关系的ICollection数据

时间:2015-05-01 14:01:26

标签: c# .net asp.net-mvc entity-framework ado.net-entity-data-model

我一直在努力在实体框架中获取ICollection值。我使用的是版本6.

类Navigation_Functions

[Table("Navigation_Functions")]
public class Navigation_Functions
{
    public Navigation_Functions()
    {}

    [Key]
    public int Function_ID { get; set; }

    [StringLength(250)]
    [Required(ErrorMessage = "Required Title")]
    [Display(Name = "Function Title")]
    public string FunctionName { get; set; }

    [Required(ErrorMessage = "Required Hierarchy Level")]
    [Display(Name = "Hierarchy Level")]
    public int Hierarchy_Level { get; set; }

    public ICollection<Navigation_FunctionController> Navigation_FunctionController { get; set; }
}

类Navigation_Controller

[Table("Navigation_FunctionController")]
public class Navigation_FunctionController
{
    public Navigation_FunctionController()
    { }

    [Key]
    public int ControllerID { get; set; }

    [StringLength(250)]
    [Required]
    public string ControllerName { get; set; }

    public ICollection<Navigation_Functions> Navigation_Functions { get; set; }

}

中产阶级打破多对多关系

[Table("Navigation_FunctionInController")]
public class Navigation_FunctionInController
{
    public Navigation_FunctionInController() 
    { 

    }

    [Key]
    public int FunctionInController_ID { get; set; }

    [Key]
    [ForeignKey("Navigation_Functions")]
    public int Function_ID { get; set; }

    [Key]
    [ForeignKey("Navigation_FunctionController")]
    public int ControllerID { get; set; }

    public Navigation_FunctionController Navigation_FunctionController { get; set; }
    public Navigation_Functions Navigation_Functions { get; set; }

}

所以当我运行以下代码时,我得到了navigation_function的所有navigation_controller

    public IEnumerable<Navigation_Functions> GetAllFunctions()
    {
        using(var _uow = new FunctionsNavigation_UnitOfWork())
        {
            var entities = _uow.Navigation_Functions_Repository.GetAll();

            return entities.ToList();
        }
    }

我将虚拟添加到模型

public virtual ICollection<Navigation_Functions> Navigation_Functions { get; set; }
public virtual ICollection<Navigation_FunctionController> Navigation_FunctionController { get; set; }

我收到以下错误以读取数据 enter image description here

2 个答案:

答案 0 :(得分:0)

您不需要创建多对多关系表,实体框架将为您执行此操作。您只需要将属性声明为虚拟属性,所有都使用include方法。 更多详情herehere

答案 1 :(得分:0)

确保将ICollection方法设置为&#34; virtual&#34; 例如     公共虚拟ICollection课程{get;组; }

这是一个例子: http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

请记住,如果交集表包含一个或多个属性(不属于主键),则不要创建交集表,只需在两个实体中使用ICollection。但是,如果交集中有一个或多个属性,则创建交集类。这就是EF Designer的工作方式。