[英]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
. 我必须代表
Message
和Topic
实体。
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
已保存 Message
ID Message
ID一起保存在MessageTopics映射表中 What I want to happen is 我想发生的是
Message
is saved Message
已保存 Message
ID Message
ID一起保存在MessageTopics表中 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();
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.