Jordan Axe
Jordan Axe

Reputation: 3923

EF inserting duplicate row even when parent is attached

My entities:

UserProfile: - Nothing of importance here.

SupportTicket: - UserProfile

SupportTicketMessage: - UserProfile - SupportTicket

My issue is that whenever I try to insert a SupportTicketMessage I get an additional UserProfile inserted into the database (a duplicate) even though I've attached the corresponding SupportTicket.

Here's my code (inside the SupportTicket class, so this means SupportTicket):

public void AddReply(UserProfile user)
{
    SupportTicketMessage msg = new SupportTicketMessage(user, this);
    using (DBContext db = new DBContext())
    {
        db.SupportTickets.Attach(msg.Ticket);
        db.SupportTicketMessages.Add(msg);
        db.SaveChanges();
     }
}

Whenever I run this the SupportTicketMessage gets inserted just fine but it inserts a duplicate UserProfile even though there's a matching one already.

What's the problem here?

Btw here's the supportticketmessage constructor:

   public SupportTicketMessage(UserProfile author, SupportTicket ticket)
    {
        Author = author;
        Ticket = ticket;
        Date = DateTime.Now;
    }

Upvotes: 3

Views: 328

Answers (1)

Slauma
Slauma

Reputation: 177133

I get an additional UserProfile inserted into the database (a duplicate) even though I've attached the corresponding SupportTicket.

Yes, you attached the corresponding SupportTicket with Attach(msg.Ticket), but where did you attach the UserProfile that's actually the duplicated entity? If msg.Ticket.UserProfile is already set to the profile you pass into AddReply then the duplication is unexpected. But it's not visible in your code snippets that msg.Ticket.UserProfile is set. If it's not set you need to attach the msg.UserProfile as well:

db.UserProfiles.Attach(msg.Author);
db.SupportTickets.Attach(msg.Ticket);
db.SupportTicketMessages.Add(msg);
db.SaveChanges();

Upvotes: 1

Related Questions