Eri*_*ric 3 c# sql sql-server entity-framework transactions
问题:我需要在多表插入中获取一个标识,我需要在Entity Framework中包含它周围的事务支持.
我有两个(伪通用的)对象与对应的表,书和作者:
create table Author
(authorid int identity primary key,
authorname varchar(max)
)
create table Book
(bookid int identity primary key,
bookname varchar(max),
authorid int references Author(authorid)
)
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我需要用新作者插入一本新书时,我最终需要做这样的事情,如果Book插入引发异常我有一个没有Book的作者,这对我的应用程序不利.
context.Authors.Add(newauthor);
context.SaveChanges();
newbook.AuthorID = newauthor.ID //I can read this now because the SaveChanges() created the ID
context.Books.Add(newbook);
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
我浏览了这篇文章,基本上说不使用与EntityFramework的事务,并建议每次操作调用一次SaveChanges()并让EF自己处理事务.我很乐意,但我需要首先从表中获取身份,如我的伪代码中所示和这个问题
问题是 - 你绝对需要插入作者的ID吗?
您可以先使用代码或使用db优先使用Entity进行开发.如果您首先使用数据库,您将拥有生成实体的.edmx文件,其中包含导航属性和集合......那么,上面的关键特征是什么,对于作者实体,您将拥有Books集合,这要归功于关系authorid int在您的表Book中引用Author(authorid).因此,要向作者添加书籍,只需制作以下内容:
//Somewhere here author is created, add it to context.Authors
context.Authors.Add(newauthor);
//Somewhere here book is created, don't need to add it to context.Books; don't call SaveChanges either
newauthor.Books.Add(newbook);// And this is all you need; ID management will be done by Entity, automatically
context.SaveChanges(); // Only one call to save changes you will need
//Of course, all IDs of inserted entities will be available here...
Run Code Online (Sandbox Code Playgroud)
类似的结构也将首先对代码有效; 在作者实体中,您很可能会public virtual ICollection<Book> Books收集.并且将以与上述相同的方式完成书的创建.
当然,你可以通过多次context.SaveChanges()获取新插入的实体的ID - 你不应该这样做.每个SaveChanges()广告只是往返于服务器的广告,并且可能最终会导致性能不佳.如上所述,最好将ID值的管理留给Entity.
并且,完成故事.使用上面的结构,EF会自动将所有内容包装到事务中的SaveChanges().因此,如果Book插入失败,Author插入也将被撤消.
| 归档时间: |
|
| 查看次数: |
3285 次 |
| 最近记录: |