实体框架:多对多关系表

时间:2013-05-03 08:46:55

标签: c# asp.net-mvc json entity-framework

我有一个新闻实体,我根据他们的新闻ID获取新闻。现在我定义了一个新实体,一个组,我希望根据他们的组ID获取新闻。我定义了一个Group news Table Aslo来将它与table联系起来。 enter image description here

在新闻模型中我有:

public virtual ICollection<GroupNews> RelatedGroupID { get; set; }

所以我假设我定义了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>();
}

}

我将此行添加到其中,以便根据GroupID定义约束。

    else if (groupId > 0)
    {
        constraint = e => (e.RelatedGroupID.Any(n => n.GroupID == groupId));
    }

这似乎不对,并且给了我这个错误:

  

{“无效的对象名称'dbo.GroupNewsNews'。”}

1 个答案:

答案 0 :(得分:5)

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

    public virtual ICollection<Group> Groups 
    { 
        get; 
        set; 
    }

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

Groups = new List<Group>();

群体实体的类似变化。

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

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

3.Write NewsRepository和GroupRepository的测试。

相关问题