实体框架工作:多对多关系表

Aid*_*a E 2 c# asp.net-mvc json entity-framework

我有一个新闻实体,我根据他们的新闻ID获取新闻.现在我定义了一个新实体,一个组,我希望根据他们的组ID获取新闻.我定义了一个Group news Table Aslo来将它与table联系起来. 在此输入图像描述

在新闻模型我有:

public virtual ICollection<GroupNews> RelatedGroupID { get; set; }
Run Code Online (Sandbox Code Playgroud)

所以我假设我定义了GroupNews表值,我可以在NewsService中使用它.

现在让我们来看看NewsService:

    Expression<Func<News, bool>> constraint = null;

    if (user_id > 0 && project_id > 0)
    {
        constraint = e => (e.CreatorID == user_id && e.RelatedProjectTags.Any(p => p.ProjectID == project_id));
    }
    else if (user_id > 0)
    {
        constraint = e => (e.CreatorID == user_id);
    }
    else if (project_id > 0)
    {
        constraint = e => (e.RelatedProjectTags.Any(p => p.ProjectID == project_id));
    }

    else
    {
        constraint = null;
    }

    IEnumerable<News> result_list = null;

    if (constraint != null)
    {
        result_list = newsRepository.GetMany(constraint).OrderByDescending(e => e.CreatedOn).Skip(offset);
    }
    else
    {
        result_list = newsRepository.GetAll().OrderByDescending(e => e.CreatedOn).Skip(offset);
    }

    if (count > 0)
    {
        result_list = result_list.Take(count);
    }

    return result_list.ToList<News>();
}
Run Code Online (Sandbox Code Playgroud)

}

我将此行添加到其中以便基于GroupID定义约束.

    else if (groupId > 0)
    {
        constraint = e => (e.RelatedGroupID.Any(n => n.GroupID == groupId));
    }
Run Code Online (Sandbox Code Playgroud)

它似乎错了,并给我这个错误:

{"无效的对象名称'dbo.GroupNewsNews'."}

Vla*_*huk 5

1.您在GroupNews表中不需要GroupNewsID.您需要删除此列并通过GroupID和NewsID创建复杂密钥.在新闻实体中,您需要定义属性:

    public virtual ICollection<Group> Groups 
    { 
        get; 
        set; 
    }
Run Code Online (Sandbox Code Playgroud)

在此实体的默认构造函数中,您需要初始化属性(需要延迟加载):

Groups = new List<Group>();
Run Code Online (Sandbox Code Playgroud)

Group实体的类似更改.

2.在GroupMap.cs中你需要定义

this.HasMany(t => t.News)
    .WithMany(t => t.Groups)
    .Map(m =>
        {
            m.ToTable("GroupNews");
            m.MapLeftKey("GroupID");
            m.MapRightKey("NewsID");
        });
Run Code Online (Sandbox Code Playgroud)

3.Write NewsRepository和GroupRepository的测试.