1

I have a scenario where parent entity already exists and I have to add it's child during the update of the parent entity, for example:

var db = new TestContext();
var book = new Book { 
    BookId = 1, // Already exists in the db from previous save operation 
    Author = new Author {
        FirstName = "Charles", 
        LastName = "Dickens" 
    } 
};
db.Attach(book);

I am getting the following error in the attach method:

The instance of entity type 'Book' 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.

Attiqe
  • 646
  • 1
  • 10
  • 22
  • 1
    Ehm, given that you're saying that the book already has an ID, does that mean that the book is the existing parent of the newly created author child? Because that would make it a counterintuitive example. And if the book is new, I'm not quite sure why you're setting its ID (and why you're creating a new author rather than refer to the existing one). Can you elaborate on the exact problem? – Flater Nov 28 '17 at 17:17
  • Book already exist in the database and I want to update the book with author and other properties. – Attiqe Nov 28 '17 at 17:22
  • 1
    So does that mean the Book is the parent, and the Author is the child? I'm asking because you said: `where parent entity already exists and I have to add it's child` , and without explicit confirmation, many people will assume that the Author is the parent and the Book is the child (as one author has many books, in a simple data model). – Flater Nov 28 '17 at 17:33
  • Book is parent and author is the child. – Attiqe Nov 28 '17 at 17:35

1 Answers1

0

Simply var book = db.Books.Find(1) where Books is the name of your DbSet<Book> instead of creating a new object.

This will give you the same entity which is stored in the database.

jeubank12
  • 891
  • 9
  • 17
  • I don't want to get it from the database and then fill it with latest data, it's too time-consuming when we have the long list of properties along with navigations. – Attiqe Nov 28 '17 at 17:09
  • In that case, use either plain sql or see this answer to a similar/duplicate question here: https://stackoverflow.com/a/12413549/1108468 – jeubank12 Nov 28 '17 at 17:50