【问题标题】:EF inserting duplicate row even when parent is attached即使附加了父级,EF也会插入重复的行
【发布时间】:2013-08-01 13:49:46
【问题描述】:

我的实体:

用户个人资料: - 这里没什么重要的。

SupportTicket: - 用户资料

SupportTicketMessage: - 用户资料 - 支持票

我的问题是,每当我尝试插入 SupportTicketMessage 时,我都会在数据库中插入一个额外的 UserProfile(重复),即使我已经附加了相应的 SupportTicket。

这是我的代码(在 SupportTicket 类中,所以 this 表示 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();
     }
}

每当我运行此程序时,SupportTicketMessage 都会被很好地插入,但它会插入一个重复的 UserProfile,即使已经有一个匹配的。

这里有什么问题?

顺便说一句,这里是 supportticketmessage 构造函数:

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

【问题讨论】:

标签: c# database visual-studio entity-framework linq-to-entities


【解决方案1】:

我在数据库中插入了一个额外的用户配置文件(一个 重复),即使我已附上相应的 SupportTicket。

是的,您在Attach(msg.Ticket) 中附加了相应的SupportTicket,但是您在哪里附加了实际上是重复实体的UserProfile?如果msg.Ticket.UserProfile 已设置为您传递给AddReply 的配置文件,则重复是意外的。但是在您的代码 sn-ps 中设置了 msg.Ticket.UserProfile 是不可见的。如果未设置,您还需要附加msg.UserProfile

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多