After several attempts, I went 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();
Although not very good, it prevents a race condition between author validation and insertion using db's own functions. ORM and leaky abstractions, eh :)
I think I, too, could insert a book insert into it, or do all this sproc. If someone comes up with their own ORM approach that fits this scenario, I'm all ears :)
ashic source share