Using no tracking navigation property EF core

user1346743 :

Let's say I have 2 tables: Books and Authors. They are represented as following EF models:

class Book {
   Guid Id { get; set; }
   string BookName { get; set; }
   Author Author { get; set; }
}

class Author {
   Guid Id { get; set; }
   string Name { get; set; }
}

Both entities have autogenerated Guid Id, i.e. before being inserted into database, Ids are generated on client site(that's default behaviour of npgsql) Book table has a foreign key to Author table. So, lets say I have a several authors already. I would like to add new book by some author. It's a web app, so I have repositories injected into controller. Before inserting new book I load (readonly, i.e AsNoTracking for performance benefits) available authors, find required author and assign that author to newly created book's Author property. On DbContext.SaveChanges I got an error, saying the given Id already exist. I suspect EF is trying to add new Author with a given ID(even though it already exist in a database) because Author entity was loaded as NoTracking.

Is there a way to load foreign key as no tracking to create new entities?

Thanks

Ivan Stoev :

The behavior of the Add method is to mark recursively as Added any non tracked entity discovered via navigation properties.

So you either has to Attach the existing related entities before calling Add, or use Entry method and set the State to Added - in EF6 this has the same effect as Add, but in EF Core it just marks the entity as Added without doing any navigation property processing.

e.g. the following will do what you are asking for:

var book = new Book { BookName = "SomeBook" };
book.Author = context.Authors.AsNoTracking().First(a => a.Name == "SomeAuthor");
context.Entry(book).State = EntityState.Added;
context.SaveChanges();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33318&siteId=1