简体   繁体   English

EF6对外键的唯一约束

[英]EF6 unique constraint on foreign key

I've got the following scenario: 我有以下场景:

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; }
}

I'm looking to insert books, and associated authors if needed. 我希望在需要时插入书籍和相关作者。 I have the following naive code, which breaks (pretty much expected): 我有以下天真的代码,它打破了(非常期待):

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();

What I'm seeing is that sometimes, the FirstOrDefault is returning null, but the insert is failing due to violation of the unique index on the author name. 我所看到的是,有时,FirstOrDefault返回null,但由于违反了作者名称上的唯一索引,插入失败。 Is there some EF trickery that'll allow this to happen in a simplistic way? 是否有一些EF技巧可以让它以简单的方式发生? I guess I could use a stored proc, but would like to do it client side if possible. 我想我可以使用存储过程,但如果可能的话,我想做客户端。

After trying various things, I've gone with the following: 在尝试了各种各样的事情之后,我选择了以下内容:

var author = _ctx.Authors.SqlQuery(
    "with data as (select @author as [name]) " +
    "merge Authors a " +
    "using data s on s.[name] = a.[name] " +
    "when not matched by target " +
    "then insert([name]) values(s.[name]); select * from Authors where [name]=@author", new SqlParameter("author", command.Author)).Single();


var book = new Book
{
    Isbn = command.Id,
    Title = command.Title,
    Stock = command.Count,
    Author = author
};

_ctx.Books.Add(book);

await _ctx.SaveChangesAsync();

While not pretty, this does prevent the race condition between the author check and insertion using db native features. 虽然不漂亮,但这确实可以防止使用db本机功能进行作者检查和插入之间的竞争条件。 ORMs and leaky abstractions, eh :) ORM和漏洞抽象,呃:)

I guess I could put the book insert in there too, or make the whole thing a sproc. 我想我也可以把书插入那里,或者把整个东西当成一个小块。 If anybody comes up with an ORM native approach that caters to this scenario, I'm all ears :) 如果有人想出一个迎合这种情况的ORM原生方法,我全都耳朵:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM