首先,在建模文件之间的引用时,您需要引用外部文档的键而不是整个文档。现在您所拥有的会将相册嵌入到文档中。请改为如下操作:
public class Photo
{
public string Id { get; set; }
public string PhotoName { get; set; }
public string AlbumId { get; set; }
}
关于级联删除,该捆绑包只是在删除文档时查看元数据并删除所有引用的文档。它不会帮助您构建那个文档列表。您必须自己完成这项工作。每次添加照片时,您都需要加载相册并将照片的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())
{
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;
}