简体   繁体   中英

C# Entity Framework set referenced entity to new parent entity

I've got a list of messages which are referenced by a command. This command can succeed or fail. Every command should be a new entity, but the message should be unique, it should always reference to the last command or to the successful command. So I've tried to delete the old message, I deleted the reference between command and message but always get this error:

The instance of entity type 'DbMessage' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

To ensure it's the same message, I use this method:

public IDbMessage FirstOrdDefaultMessage(Func<IDbMessage, bool> predicate)
{
    var attached = _context.Messages.Local.FirstOrDefault(predicate);

    if (attached == null)
        attached = _context.Messages.FirstOrDefault(predicate);

    return attached;
}

But I still get the error. It even returns the message on local but only once but there should be two.

Entity Framework by default tracks entities, if your operation is readonly you should always use.AsNoTracking(). This error is caused, because you were tracking an instance of DbMessage. If you try to get (and track) the same instance from the database you will get this error.

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.

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