ln.types/odb/ng/ODBMapper.API.cs

88 lines
2.2 KiB
C#

using ln.types.btree;
using System.Collections.Generic;
using System;
namespace ln.types.odb.ng
{
public partial class ODBMapper
{
BTree<Guid, CachedObject> forwardCache = new BTree<Guid, CachedObject>();
Dictionary<object, CachedObject> reverseCache = new Dictionary<object, CachedObject>();
public T Load<T>(Guid documentID) => (T)Load(typeof(T), documentID);
public object Load(Type type,Guid documentID)
{
lock (this)
{
if (forwardCache.ContainsKey(documentID))
return forwardCache[documentID].Instance;
IStorage storage = StorageContainer.GetStorage(type.FullName);
Document document = storage.Load(documentID);
object instance = ObjectMapping.UnmapValue(this, document);
CachedObject cachedObject = new CachedObject(document, instance);
forwardCache.Add(cachedObject.Document.ID,cachedObject);
reverseCache.Add(cachedObject.Instance, cachedObject);
return cachedObject.Instance;
}
}
public void Save<T>(T instance) => Save(typeof(T), instance);
public void Save(Type type,object instance)
{
lock (this)
{
IStorage storage = StorageContainer.GetStorage(type.FullName);
CachedObject cachedObject;
Document document;
if (reverseCache.ContainsKey(instance))
{
cachedObject = reverseCache[instance];
document = (GetMapping(type) as mappings.ClassMapping).MapDocument(this, cachedObject.Document.ID, instance);
storage.Save(document);
cachedObject.Document = document;
}
else
{
document = (GetMapping(type) as mappings.ClassMapping).MapDocument(this, Guid.NewGuid() ,instance) as Document;
cachedObject = new CachedObject(document, instance);
storage.Save(document);
forwardCache.Add(cachedObject.Document.ID, cachedObject);
reverseCache.Add(instance, cachedObject);
}
}
}
public IEnumerable<Guid> GetDocumentIDs<T>() => GetDocumentIDs(typeof(T));
public IEnumerable<Guid> GetDocumentIDs(Type type)
{
IStorage storage = StorageContainer.GetStorage(type.FullName);
return storage.GetDocumentIDs();
}
struct CachedObject
{
public object Instance;
public Document Document;
public CachedObject(Document document, object instance)
{
Document = document;
Instance = instance;
}
}
}
}