Рассмотрите следующий код :
Код: Выделить всё
public class Book
{
public Book()
{
this.Id = Guid.NewGuid();
this.Authors = new List();
}
public virtual Guid Id { get; protected set; }
public virtual ICollection Authors { get; set; }
public void AddAuthor(Author author)
{
author.BookId = this.Id;
this.Authors.Add(author);
}
}
public class Author
{
public Author()
{
this.Id = Guid.NewGuid();
}
public virtual Guid Id { get; protected set; }
public virtual Guid BookId { get; set; }
public virtual Book Book { get; set; }
}
Код: Выделить всё
var book = new Book();
context.Books.Add(book);
context.SaveChanges();
book = context.Books.First();
var author = new Author();
book.Authors.Add(author);
context.SaveChanges();
'Попытка обновить или удалить объект, которого нет в магазине.'
Если я проверю ChangeTracker DbContext, Я действительно вижу, что сущность "Автор" помечена как "Изменено", а не "Добавлено".
Однако следующее работает нормально:
Код: Выделить всё
var book = new Book();
context.Books.Add(book);
context.SaveChanges();
book = context.Books.First();
var author = new Author() { BookId = book.Id };
context.Authors.Add(author);
context.SaveChanges();
Заранее спасибо!
Подробнее здесь: https://stackoverflow.com/questions/594 ... -the-store
Мобильная версия