c# - Entity Framework : many to many relationship , 插入和更新

标签 c# entity-framework

我有一个新闻实体,我根据他们的 NewsID 获取新闻。然后我定义了一个新实体,一个组,我想根据他们的组 ID 获取新闻。我尝试使用 this article 处理这种(多对多)关系通过使用代码优先方法。

enter image description here

所以在我的上下文中我添加了:

 public class Groupnews : DbContext
    {

        public DbSet<Group> Group { get; set; }
        public DbSet<News> News { get; set; }

        public Groupnews()
            : base("MyDb")
        {
        }

        public int NewsID { get; set; }
    }

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

现在我可以使用这种方法根据他们的 GroupID 获取新闻。但问题在于插入新新闻和更新。为此,我需要将 NewsID 和 GroupId 保存在 GroupNews 表中。为此。在我定义的新闻模型中:

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

    public News()
    {
        RelatedGroups = new List<Group>();
    }

组也一样:

    public virtual ICollection<News> RelatedNews { get; set; }
    public Group()
    {
        RelatedNews = new List<News>();
     }

在我的新闻 Controller 中,我添加:

            Group group = new Group();
            group.RelatedNews.Add(news);

enter image description here

但没有任何更新,NewsID 也没有添加到我的 GroupNews 表中。

最佳答案

您不应该单独定义 GroupNews。也就是说,您不应在项目中定义 GroupNews 类。您必须使用独立关联(Group 类中的 News 列表和 News< 中的 Group 列表来执行 CRUD 操作类)。您的类(class)应该如下所示:

public class Group
{
    ...
    public Group()
    {
         this.News = new List<News>();
    }

    public virtual ICollection<News> News {get;set;}
}

public class News
{
    ...
    public News()
    {
         this.Group = new List<Group>();
    }
    public virtual ICollection<Group> Groups {get;set;}
}

public class MyContext : DbContext
{
    public DbSet<Group> Groups { get; set; }
    public DbSet<News> News { get; set; }
}

然后您可以使用 myGroup.News.Add(myNewsItem)myNews.Groups.Add(myGroup)。 Entity Framework 将自动处理插入。请注意,如果要为关联启用延迟加载,则应使用 virtual 关键字。

关于c# - Entity Framework : many to many relationship , 插入和更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545550/

相关文章:

c# - 如何处理 MSTest 中的 IDisposable fixture 成员?

c# - 在 dapper 中查询抽象模型

c# - jquery 拖放与 asp.net c# 功能

c# - 任务栏上的子组

entity-framework - Entity Framework : Setting update timestamp

c# - 如何在 Linq toEntity 中将字符串数组转换为字符串?

c# - 如何使用 C# 获取 Excel 工作表中给定行的列数?

c# - 当连接条件类似时如何在 EF 中进行连接

c# - EF Core 预加载返回 null

c# - TransactionScope 问题和 EF6 异步调用