EF6对外键的唯一约束

时间:2015-12-20 14:35:35

标签: c# entity-framework-6

我有以下情况:

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 ICollection<Book> Books { 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技巧可以让它以简单的方式发生?我想我可以使用存储过程,但如果可能的话,我想在客户端进行。

0 个答案:

没有答案