I have a database model where there is a link between the models that gives Code First some problems. The following is an example of construction.
One reader could read several books, and one book could be read by several readers. In addition, each reader may have a favorite book.
//not-working model public class BookReader { public virtual List<Book> ReadBooks { get; set; } public virtual Book FavoriteBook { get; set; } public int ID { get; set; } } public class Book { public string BookName { get; set; } public int ID { get; set; } }
This is not good. If in the code several readers are configured to read the same book, only one of the readers will receive it in db (presumably the last set).
Also, if BookReader.FavoriteBook and BookReader.ReadBooks contain the same book, and db.SaveChanges () creates this new book (and not the existing db object), this will result in this error:
An error occurred while saving objects that do not disclose foreign key properties for their relationships.
Here is my fix with InverseProperty and navigation properties.
//working model public class BookReader { [InverseProperty("CurrentReaders")] public virtual List<Book> ReadBooks { get; set; } public virtual Book FavoriteBook { get; set; } public int ID { get; set; } } public class Book { public string BookName { get; set; } public int ID { get; set; } //new, unwanted, property public virtual List<BookReader> CurrentReaders { get; set; } }
I do not want to change the model as follows. Can this be done using the Fluent API without changing the model?
I posted a similar question earlier, but deleted it because the question turned out to be irrelevant for the problem
source share