【问题标题】:Entity frame work: many to many relationship tables实体框架:多对多关系表
【发布时间】:2013-05-03 08:46:54
【问题描述】:

我有一个新闻实体,我根据他们的 NewsID 获取新闻。现在我定义了一个新实体,一个 Group,我想根据他们的 Group ID 获取新闻。我定义了一个 Group news Table Aslo 来将它与表关联起来。

在新闻模型中我有:

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'。"}

【问题讨论】:

  • 如果您使用 Code First,为什么不让 EF 为您生成数据库。无需手动创建/更改数据库表。
  • 请发布您的GroupNewsNews 课程以及您的上下文课程。
  • 根据您的屏幕截图和错误消息,您的表名为 GroupNews,但 EF 正在尝试查找 GroupNewsNews。您可能需要覆盖表名:[Table["GroupNews")]

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


【解决方案1】:

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

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

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

Groups = new List<Group>();

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.为 NewsRepository 和 GroupRepository 编写测试。

【讨论】:

  • 但是 GroupNews 表的主键是什么?
  • GroupIDNewsID这两个外键的组合就是主键。
  • 当我添加新新闻时,如何将相关的 groupID 和 newsID 添加到 GroupNews Table 中?
  • 但它不起作用。每次我添加新闻时,相关的 groupID 和 NewsId 都不会添加到 GroupNews 表中
猜你喜欢
  • 2017-01-28
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多