首先,在对文档之间的引用进行建模时,您需要引用外部文档键,而不是整个文档。您现在拥有的内容会将相册嵌入到文档中。改为这样做:
public class Photo
{
public string Id { get; set; }
public string PhotoName { get; set; }
public string AlbumId { get; set; }
}
关于级联删除,bundle 在删除文档时只查看元数据并删除任何引用的文档。它不能帮助您建立开始的文档列表。你必须自己做。每次添加照片时,都会加载相册并将照片的 Id 添加到相册的级联删除列表中。
因此,在保存相册和前几张照片时:
using (var session = documentStore.OpenSession())
{
var album = new Album();
session.Store(album);
var photoA = new Photo { PhotoName = "A", AlbumId = album.Id };
var photoB = new Photo { PhotoName = "B", AlbumId = album.Id };
var photoC = new Photo { PhotoName = "C", AlbumId = album.Id };
session.Store(photoA);
session.Store(photoB);
session.Store(photoC);
session.Advanced.AddCascadeDeleteReference(album,
photoA.Id,
photoB.Id,
photoC.Id);
session.SaveChanges();
}
稍后,将照片添加到现有相册
using (var session = documentStore.OpenSession())
{
// you would know this already at this stage
const string albumId = "albums/1";
var photoD = new Photo { PhotoName = "D", AlbumId = albumId };
session.Store(photoD);
var album = session.Load<Album>(albumId);
session.Advanced.AddCascadeDeleteReference(album, photoD.Id);
session.SaveChanges();
}
这是AddCascadeDeleteReference
我上面使用的扩展方法。你可以自己做,但这会让事情变得更容易一些。把它放在一个静态类中。
public static void AddCascadeDeleteReference(
this IAdvancedDocumentSessionOperations session,
object entity, params string[] documentKeys)
{
var metadata = session.GetMetadataFor(entity);
if (metadata == null)
throw new InvalidOperationException(
"The entity must be tracked in the session before calling this method.");
if (documentKeys.Length == 0)
throw new ArgumentException(
"At least one document key must be specified.");
const string metadataKey = "Raven-Cascade-Delete-Documents";
RavenJToken token;
if (!metadata.TryGetValue(metadataKey, out token))
token = new RavenJArray();
var list = (RavenJArray) token;
foreach (var documentKey in documentKeys.Where(key => !list.Contains(key)))
list.Add(documentKey);
metadata[metadataKey] = list;
}