我有以下场景:
public class Book { [Key] public string Isbn { get; set; } public string Title { get; set; } public int Stock { get; set; } public Author Author { get; set; } } public class Author { public int AuthorId { get; set; } [Index(IsUnique = true)] [StringLength(50)] public string Name { get; set; } public ICollectionBooks { get; set; } }
我希望在需要时插入书籍和相关作者.我有以下天真的代码,它打破了(非常期待):
var author = _ctx.Authors.FirstOrDefault(x => x.Name == command.Author); if (author == null) author = new Author { Name = command.Author }; var book = new Book { Isbn = command.Id, Title = command.Title, Stock = command.Count, Author = author }; _ctx.Books.Add(book); await _ctx.SaveChangesAsync();
我所看到的是,有时,FirstOrDefault返回null,但由于违反了作者名称上的唯一索引,插入失败.是否有一些EF技巧可以让它以简单的方式发生?我想我可以使用存储过程,但如果可能的话,我想做客户端.