我試圖通過CascadeDelete RavenDB軟件包嵌入RavenDB,但該軟件包似乎沒有被激活,在這個應用程序中實現級聯刪除。我應該怎麼做呢?如何集成嵌入式RavenDB和CascadeDelete包?
在下面的代碼片段是一個測試控制檯應用程序,試圖在嵌入式/內存RavenDB數據庫中啓用級聯刪除,我已經安裝了NuGet包RavenDB.Embedded 2.5.2505-Unstable和RavenDB.Bundles.CascadeDelete 2.5 0.2505不穩定吧:
using System;
using System.Linq;
using Raven.Client;
using Raven.Client.Embedded;
using Raven.Json.Linq;
namespace ConsoleApplication1
{
public class Parent
{
public string Id { get; set; }
}
public class Child
{
public string Id { get; set; }
public string ParentId { get; set; }
}
public static class RavenExtensions
{
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;
}
}
class Program
{
static void Main(string[] args)
{
var store = new EmbeddableDocumentStore { RunInMemory = true };
store.Initialize();
Parent parent;
using (var session = store.OpenSession())
{
parent = new Parent();
session.Store(parent);
session.SaveChanges();
var child = new Child();
child.ParentId = parent.Id;
session.Store(child);
session.Advanced.AddCascadeDeleteReference(parent, child.Id);
session.SaveChanges();
}
using (var session = store.OpenSession())
{
Console.WriteLine("Before deleting parent:");
foreach (var child in session.Query<Child>())
{
Console.WriteLine(" Child: {0} of parent {1}", child.Id, child.ParentId);
}
parent = session.Load<Parent>(parent.Id);
session.Delete(parent);
session.SaveChanges();
Console.WriteLine("After deleting parent:");
foreach (var child in session.Query<Child>())
{
Console.WriteLine(" Child: {0} of parent {1}", child.Id, child.ParentId);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
}
當你運行這個程序,你應該看到的是,孩子是不是與父刪除,即使它被配置爲通過級聯刪除。請指出我怎樣才能使級聯刪除這個程序:)工作
更新:
我試着加入以下後store.Initialize();
,但它並沒有區別:
store.DocumentDatabase.Configuration.Catalog.Catalogs.Add(
new AssemblyCatalog(typeof(CascadeDeleteTrigger).Assembly));
如果您想避免這種情況,請參閱我的答案中的選項#2。 – 2013-02-21 14:45:31