我有控制器方法来添加一本书:
[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);
}
}
在图书服务中,它从BookDto映射到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; }
}
问题是,我无法添加书,EF对此有异议:
Microsoft.Data.SqlClient.SqlException(0x80131904):违反 主键约束'PK_Authors'。无法在其中插入重复的密钥 对象“ dbo.Authors”。重复的键值为 (94cf4d6a-b6bc-4015-acee-2345438ee912)。该声明已经 终止。
但是当出现异常时,如何使用现有作者和类别添加新书?
答案 0 :(得分:0)
在bookservice.addbook或自动映射器配置文件中,仅将书籍的AuthorId设置为不是整个Author实体(将其设置为null),或将Author的实体标记为不变。
context.Entry(book.Author).State = EntityState.Unchanged;
context.Entry(book.Category).State = EntityState.Unchanged;
您的图书实体应具有CategoryId和AuthorId
答案 1 :(得分:-1)
错误很明显,您正在尝试插入具有现有ID的书。问题可能出在Guid生成器或mapper。