简体   繁体   English

将现有实体添加到多对多关系的子级集合中

[英]Adding an existing entity to a child collection of a many-to-many relationship

I have to entities that represent a Message and a Topic . 我必须代表MessageTopic实体。
A Message can have many Topic , and a Topic can belong to many Message 一个Message可以有多个Topic ,而一个Topic可以属于多个Message

public class Message
{
    [Key]
    public int Id { get; set; }

    public string Text { get; set; }

    public virtual ICollection<Message> Topics { get; set; }
}

public class Topic
{
    public int Id { get; set; }

    public string Value { get; set; }

    public virtual ICollection<Message> Messages { get; set; }
}

In my application, we first save Topic (early on in the application, sometimes seed data etc...) 在我的应用程序中,我们首先保存Topic (在应用程序中较早,有时是种子数据等)。

Later, I need to save a new Message - adding an already existing Topic to the child collection; 稍后,我需要保存一个Message -向Topic添加一个已经存在的Topic

var message = new Message();
message.Text = "Hello";
//this topic already exists in the database
message.Topics.Add(new Topic{Id = 6, Value = "val"}); 
dbContext.Messages.Add(message);
dbContext.SaveChanges();

What happens is: 发生的是:

  • Message is saved Message已保存
  • New topic is created (with Value of "val") 创建主题(值为“ val”)
  • ID of new topic is saved in MessageTopics mapping table against the newly created Message ID 主题的ID与新创建的Message ID一起保存在MessageTopics映射表中

What I want to happen is 我想发生的是

  • Message is saved Message已保存
  • ID of supplied topic (6 in this case) is saved in MessageTopics table against the newly created Message ID 所提供主题的ID(在这种情况下为6)与新创建的Message ID一起保存在MessageTopics表中

First option 第一选择

If everything is mapped correctly then the only thing you need to do is to hold reference to topic and set its state to Unchanged : 如果所有内容都正确映射,那么您唯一需要做的就是保留对topic的引用 ,并将其状态设置为Unchanged

// This topic already exists in the database.
// No need to set value.
var topic = new Topic{ Id = 6 };
var message = new Message();
message.Text = "Hello"; 
message.Topics.Add(topic); 
dbContext.Messages.Add(message);

// Set state of topic to Unchanged
dbContext.Entry(topic).State = EntityState.Unchanged;
dbContext.SaveChanges();

Second option. 第二种选择。

Just get topic from database if there is not too much data. 如果没有太多数据,只需从数据库中获取主题。

// Get topic from source
var topic = dbContext.Topics.FirstOrDefault(m => m.Id == 6);
var message = new Message();
message.Text = "Hello";
message.Topics.Add(topic); 
dbContext.Messages.Add(message);
dbContext.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM