首先,您必须遵守在 BLL 中指定为单个方法的原子工作单元。这将(例如)创建客户、订单和订单项目。然后,您可以将这一切整齐地包装在 TransactionScope using 语句中。 TransactionScope 是这里的秘密武器。下面是一些代码,幸运的是我现在正在处理:):
public static int InsertArtist(Artist artist)
{
if (artist == null)
throw new ArgumentNullException("artist");
int artistid = 0;
using (TransactionScope scope = new TransactionScope())
{
// insert the master Artist
/*
we plug the artistid variable into
any child instance where ArtistID is required
*/
artistid = SiteProvider.Artist.InsertArtist(new ArtistDetails(
0,
artist.BandName,
artist.DateAdded));
// insert the child ArtistArtistGenre
artist.ArtistArtistGenres.ForEach(item =>
{
var artistartistgenre = new ArtistArtistGenreDetails(
0,
artistid,
item.ArtistGenreID);
SiteProvider.Artist.InsertArtistArtistGenre(artistartistgenre);
});
// insert the child ArtistLink
artist.ArtistLinks.ForEach(item =>
{
var artistlink = new ArtistLinkDetails(
0,
artistid,
item.LinkURL);
SiteProvider.Artist.InsertArtistLink(artistlink);
});
// insert the child ArtistProfile
artist.ArtistProfiles.ForEach(item =>
{
var artistprofile = new ArtistProfileDetails(
0,
artistid,
item.Profile);
SiteProvider.Artist.InsertArtistProfile(artistprofile);
});
// insert the child FestivalArtist
artist.FestivalArtists.ForEach(item =>
{
var festivalartist = new FestivalArtistDetails(
0,
item.FestivalID,
artistid,
item.AvailableFromDate,
item.AvailableToDate,
item.DateAdded);
SiteProvider.Festival.InsertFestivalArtist(festivalartist);
});
BizObject.PurgeCacheItems(String.Format(ARTISTARTISTGENRE_ALL_KEY, String.Empty, String.Empty));
BizObject.PurgeCacheItems(String.Format(ARTISTLINK_ALL_KEY, String.Empty, String.Empty));
BizObject.PurgeCacheItems(String.Format(ARTISTPROFILE_ALL_KEY, String.Empty, String.Empty));
BizObject.PurgeCacheItems(String.Format(FESTIVALARTIST_ALL_KEY, String.Empty, String.Empty));
BizObject.PurgeCacheItems(String.Format(ARTIST_ALL_KEY, String.Empty, String.Empty));
// commit the entire transaction - all or nothing
scope.Complete();
}
return artistid;
}
希望你能明白要点。基本上,这是一个全部成功或失败的工作,无论任何不同的数据库(即在上面的示例中,艺术家和艺术家艺术家流派可以托管在两个单独的数据库存储中,但 TransactionScope 不太关心这一点,它在 COM+ 级别工作并管理原子性它可以“看到”的范围)
希望这可以帮助
EDIT:您可能会发现 TransactionScope 的初始调用(在应用程序启动时)可能会稍微引人注目(即在上面的示例中,如果第一次调用,可能需要 2-3 秒才能完成),但是后续调用是almost瞬时(即通常 250-750 毫秒)。简单的接触点交易与(笨拙的)替代方案之间的权衡可以减轻(对于我和我的客户而言)初始“加载”延迟。
只是想证明,轻松并非没有妥协(尽管处于初始阶段)