public async Task Add(Chat chat) { var userEntities = chat.Users.Select(x => new…
- User
public async Task Add(Chat chat) { var userEntities = chat.Users.Select(x => new UserEntity { Id = x.Id, }).ToList();
codeuserEntities.ForEach(x => _context.Users.Attach(x)); var messageEntities = chat.Messages.Select(x => new MessageEntity { Text = x.Text, User = new UserEntity { Id = x.User.Id } }).ToList(); var chatEntity = new ChatEntity { Name = chat.Name, Users = userEntities, Type = chat.Type, Messages = messageEntities }; await _context.Chats.AddAsync(chatEntity); await _context.SaveChangesAsync();}
Как тут исправить ошибку The instance of entity type 'UserEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
- Assistant
The error "The instance of entity type 'UserEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked" typically occurs in Entity Framework Core when you try to attach an entity to the context that EF is already tracking. This usually happens because you are creating new instances of your objects while EF is already tracking other instances of these objects with the same .