User1520731567 posted
Hi simpleprogrammer,
When I register an author, he saves it in the database, but when I want to register a book, he marks me an error.
System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
InvalidOperationException: A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
I have a foreign key that refers to authors in the book table:
Id_autor int foreign key references autor(ID)
According to your description,when you try to add the record there is a reference constraint violation.
When you add a book record,you need to select a author id that clarify who this book belongs to.
I suggest you could add a scaffolded item to meet your needs quickly.
You could follow the steps below:
Right click on Controllers -> Choose Add -> Choose 'MVC5 Controller with views, using Entity Framework', then Add-> Choose the Model you want to add CRUD to in 'Model class', then Add -> The controller with CRUD function is created.
Then the Index,Details,Edit,Create ..pages will be automatically generated.And compare with your code.
Actually,you could use
one to many entity.
For example:
public class author
{
public author()
{
book = new List<book>();
}
[Key]
public int Author_id { get; set; }
public string Name { get; set; }
public List<book> book { get; set; }
}
public class book
{
public int Id { get; set; }
public string Title { get; set; }
public string Publisher { get; set; }
public int Author_id { get; set; }
[ForeignKey("Author_id")]
public virtual author author { get; set; }
}
If you have any questions,please post more details,so that I can understand what your mean better.
Best Regards.
Yuki Tao