I have controller method to add a book:
[HttpPost()]
public IActionResult AddBook([FromBody] BookPL book)
{
if (!ModelState.IsValid)
{
return StatusCode(400, "Model is not valid");
}
try
{
book.BookId = Guid.NewGuid();
var newBook = mapper.Map<BookDto>(book);
booksService.AddBook(newBook);
return StatusCode(201, "Book was added");
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error. Book is not added. Exception message: " + ex);
}
}
in book service it maps from BookDto to model for EF:
public class Book
{
public Guid BookId { get; set; }
public bool IsAvailable { get; set; }
public virtual Category Category { get; set; }
public virtual Author Author { get; set; }
[Required]
[MaxLength(150, ErrorMessage = "Name length must be less then 150 characters")]
public string Name { get; set; }
[Required]
[MaxLength(2500, ErrorMessage = "Description length must be less then 2500 characters")]
public string Description { get; set; }
}
Problem is, I can't add a book, EF argues at me with this exception:
Microsoft.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_Authors'. Cannot insert duplicate key in object 'dbo.Authors'. The duplicate key value is (94cf4d6a-b6bc-4015-acee-2345438ee912). The statement has been terminated.
But how can I add a new book using existing authors and categories when it throws exception?
In bookservice.addbook or in the automapper profile, only set the books AuthorId not the entire Author entity (leave it null) or mark the entity for the Author unchanged.
context.Entry(book.Author).State = EntityState.Unchanged;
context.Entry(book.Category).State = EntityState.Unchanged;
your book entity should have a CategoryId and an AuthorId
The error is clear, you are trying insert a book with an existing Id. The problem can be the Guid generator or the mapper.
User contributions licensed under CC BY-SA 3.0