110 lines
3.1 KiB
C#
110 lines
3.1 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using ln.types.odb.values;
|
|
namespace ln.types.odb
|
|
{
|
|
public class ODBCollection<T> : IEnumerable<T> where T:class
|
|
{
|
|
public ODB ODB { get; }
|
|
public Type ElementType { get; }
|
|
|
|
ODBCollection collection;
|
|
Dictionary<ODBValue, WeakReference<T>> objectCache = new Dictionary<ODBValue, WeakReference<T>>();
|
|
|
|
internal ODBCollection(ODB odb)
|
|
{
|
|
ODB = odb;
|
|
ElementType = typeof(T);
|
|
collection = new ODBCollection(odb, ElementType.FullName);
|
|
}
|
|
|
|
public T this[ODBValue documentID]
|
|
{
|
|
get => Select(documentID);
|
|
}
|
|
|
|
|
|
public T GetCachedObject(ODBValue documentID)
|
|
{
|
|
if (objectCache.ContainsKey(documentID))
|
|
{
|
|
T o = null;
|
|
if (objectCache[documentID].TryGetTarget(out o))
|
|
return o;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public void TouchCache(ODBValue documentID,T o)
|
|
{
|
|
if ((o == null)&&objectCache.ContainsKey(documentID))
|
|
{
|
|
objectCache.Remove(documentID);
|
|
}
|
|
else if (o != null)
|
|
{
|
|
objectCache[documentID] = new WeakReference<T>(o);
|
|
}
|
|
}
|
|
|
|
public T SelectOne(string fieldName, object value)
|
|
{
|
|
ODBDocument document = collection.FindOne(fieldName, ODBMapper.Default.MapValue(value));
|
|
if (document != null)
|
|
{
|
|
return Select(document.ID);
|
|
}
|
|
return null;
|
|
}
|
|
public IEnumerable<T> Select(string fieldName, object value)
|
|
{
|
|
foreach (ODBDocument document in collection.Find(fieldName, ODBMapper.Default.MapValue(value)))
|
|
{
|
|
yield return Select(document.ID);
|
|
}
|
|
}
|
|
|
|
public T Select(ODBValue documentID)
|
|
{
|
|
T o = GetCachedObject(documentID);
|
|
if (o == null)
|
|
{
|
|
ODBDocument document = collection.GetDocumentByID(documentID);
|
|
o = ODBMapper.Default.ToNativeValue<T>(document);
|
|
TouchCache(documentID, o);
|
|
}
|
|
return o;
|
|
}
|
|
|
|
public bool Insert(T o)
|
|
{
|
|
ODBDocument document = ODBMapper.Default.MapValue(o) as ODBDocument;
|
|
return collection.Insert(document);
|
|
}
|
|
public bool Update(T o)
|
|
{
|
|
ODBDocument document = ODBMapper.Default.MapValue(o) as ODBDocument;
|
|
return collection.Update(document);
|
|
}
|
|
public bool Upsert(T o)
|
|
{
|
|
ODBDocument document = ODBMapper.Default.MapValue(o) as ODBDocument;
|
|
return collection.Upsert(document);
|
|
}
|
|
|
|
public IEnumerator<T> GetEnumerator()
|
|
{
|
|
foreach (ODBValue documentID in collection.Index)
|
|
{
|
|
yield return Select(documentID);
|
|
}
|
|
}
|
|
|
|
IEnumerator IEnumerable.GetEnumerator()
|
|
{
|
|
return GetEnumerator();
|
|
}
|
|
}
|
|
}
|