How to add complex class object to DB via EF Core, object got from client

0

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?

asp.net
entity-framework
asp.net-core
entity-framework-core
asked on Stack Overflow Dec 15, 2019 by Alex

2 Answers

0

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

answered on Stack Overflow Dec 17, 2019 by Robert Raboud
-1

The error is clear, you are trying insert a book with an existing Id. The problem can be the Guid generator or the mapper.

answered on Stack Overflow Dec 15, 2019 by Mais1

User contributions licensed under CC BY-SA 3.0