I have a problem when saving a new entity into the database. Whenever I save the new entity DbEntityValidationException occurs. But carefully looking at the values of the variable and the data annotations of my entity, I meet all of them.
I looked at the database and problem seems to be not on the entity I am adding, but on the previous entities saved in the database. For some reason, some of the foreign key fields which previously have values before the adding of entity are now NULL!
During debugging, I scanned all of these entities and before I call SaveChanges() method, those fields are there and not null. Then after calling SaveChanges(), the validation error occurs because I think SaveChanges() might have done something that made the other records mess up.
I don't know if this has something to do with it but when I create a new entity, I create a new instance of it and assign its property individually. Some of it's property came from entity framework and are attached. So I am assigning an attached property to a detached new object. I don't know if this caused the weird behavior. Here is an example excerpt:
Book book = new Book();
book.Title = "The FooBar";
book.Publisher = publisherRepository.Get(1); // will retrieve a Publisher object from EF
bookRepository.Add(book);
....
// under BookRepository class
public void Add(Book book)
{
dbContext.Books.Add(book);
// just to check if the other records are not messed up, I did this and
// check the values in VS Debugger
// At this point, the other records are not yet affected.
var books = dbContext.Books.Include("Publisher").ToArray();
dbContext.SaveChanges(); // error thrown here,
// checking at the validation error, other book
//instances have their Publisher property set to NULL!
}
Please help as I can't find other solution to this problem. I am an Entity Framework newbie myself.
publisherRepository.Get(1)?SaveChanges(), the OTHER previously valid entities have their Publisher property NULL. I don't know what caused it since I am not updating them prior to adding of the new entity.publisherRepository.Get(1)simply retrieves aPublisherinstance from db with the id of 1.