I have to entities that represent a Message
and a Topic
.
A Message
can have many Topic
, and a Topic
can belong to many 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...)
Later, I need to save a new Message
- adding an already existing Topic
to the child collection;
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
ID What I want to happen is
Message
is saved Message
ID 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
:
// 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.