Skip to content

Allow generic dictionaries for dynamic entities #1767

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions doc/reference/modules/persistent_classes.xml
Original file line number Diff line number Diff line change
Expand Up @@ -254,12 +254,12 @@ namespace Eg
<para>
Persistent entities don't necessarily have to be represented as POCO classes
at runtime. NHibernate also supports dynamic models
(using <literal>Dictionaries</literal> of <literal>Dictionary</literal>s at runtime) . With this approach, you don't
(using <literal>Dictionaries</literal>). With this approach, you don't
write persistent classes, only mapping files.
</para>

<para>
The following examples demonstrates the representation using <literal>Map</literal>s (Dictionary).
The following examples demonstrates the representation using <literal>Dictionaries</literal>.
First, in the mapping file, an <literal>entity-name</literal> has to be declared
instead of a class name:
</para>
Expand Down Expand Up @@ -305,7 +305,7 @@ namespace Eg
</para>

<para>
At runtime we can work with <literal>Dictionaries</literal> of <literal>Dictionaries</literal>:
At runtime we can work with <literal>Dictionaries</literal>:
</para>

<programlisting><![CDATA[using(ISession s = OpenSession())
Expand Down Expand Up @@ -336,6 +336,20 @@ using(ITransaction tx = s.BeginTransaction())
to the NHibernate mapping, the database schema can easily be normalized and sound,
allowing to add a proper domain model implementation on top later on.
</para>

<para>
A loaded dynamic entity can be manipulated as an <literal>IDictionary</literal> or
<literal>IDictionary&lt;string, object&gt;</literal>.
</para>

<programlisting><![CDATA[using(ISession s = OpenSession())
using(ITransaction tx = s.BeginTransaction())
{
var customers = s
.CreateQuery("from Customer")
.List<IDictionary<string, object>>();
...
}]]></programlisting>
</sect1>

<sect1 id="persistent-classes-tuplizers" revision="1">
Expand All @@ -357,9 +371,9 @@ using(ITransaction tx = s.BeginTransaction())
</para>

<para>
Users may also plug in their own tuplizers. Perhaps you require that a <literal>System.Collections.IDictionary</literal>
implementation other than <literal>System.Collections.Hashtable</literal> be used while in the
dynamic-map entity-mode; or perhaps you need to define a different proxy generation strategy
Users may also plug in their own tuplizers. Perhaps you require that a <literal>IDictionary</literal>
implementation other than <literal>System.Collections.Generic.Dictionary&lt;string, object&gt;</literal>
is used while in the dynamic-map entity-mode; or perhaps you need to define a different proxy generation strategy
than the one used by default. Both would be achieved by defining a custom tuplizer
implementation. Tuplizers definitions are attached to the entity or component mapping they
are meant to manage. Going back to the example of our customer entity:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@

using System.Collections;
using System.Collections.Generic;
using NHibernate.Cfg;
using NHibernate.Engine;
using Antlr.Runtime.Misc;
using NUnit.Framework;
using NHibernate.Criterion;

Expand All @@ -29,7 +28,7 @@ protected override string MappingsAssembly

protected override IList Mappings
{
get { return new string[] {"EntityModeTest.Map.Basic.ProductLine.hbm.xml"}; }
get { return new[] {"EntityModeTest.Map.Basic.ProductLine.hbm.xml"}; }
}

public delegate IDictionary SingleCarQueryDelegate(ISession session);
Expand Down Expand Up @@ -110,5 +109,84 @@ public async Task ShouldWorkWithCriteriaAsync()
await (t.CommitAsync(cancellationToken));
}
}

[Test]
public async Task ShouldWorkWithHQLAndGenericsAsync()
{
await (TestLazyDynamicClassAsync(
s => s.CreateQuery("from ProductLine pl order by pl.Description").UniqueResult<IDictionary<string, object>>(),
s => s.CreateQuery("from Model m").List<IDictionary<string, object>>()));
}

[Test]
public async Task ShouldWorkWithCriteriaAndGenericsAsync()
{
await (TestLazyDynamicClassAsync(
s => s.CreateCriteria("ProductLine").AddOrder(Order.Asc("Description")).UniqueResult<IDictionary<string, object>>(),
s => s.CreateCriteria("Model").List<IDictionary<string, object>>()));
}

public async Task TestLazyDynamicClassAsync(
Func<ISession, IDictionary<string, object>> singleCarQueryHandler,
Func<ISession, IList<IDictionary<string, object>>> allModelQueryHandler, CancellationToken cancellationToken = default(CancellationToken))
{
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var cars = new Dictionary<string, object> { ["Description"] = "Cars" };

var monaro = new Dictionary<string, object>
{
["ProductLine"] = cars,
["Name"] = "Monaro",
["Description"] = "Holden Monaro"
};

var hsv = new Dictionary<string, object>
{
["ProductLine"] = cars,
["Name"] = "hsv",
["Description"] = "Holden hsv"
};

var models = new List<IDictionary<string, object>> {monaro, hsv};

cars["Models"] = models;

await (s.SaveAsync("ProductLine", cars, cancellationToken));
await (t.CommitAsync(cancellationToken));
}

using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var cars = singleCarQueryHandler(s);
var models = (IList<object>) cars["Models"];
Assert.That(NHibernateUtil.IsInitialized(models), Is.False);
Assert.That(models.Count, Is.EqualTo(2));
Assert.That(NHibernateUtil.IsInitialized(models), Is.True);
s.Clear();
var list = allModelQueryHandler(s);
foreach (var dic in list)
{
Assert.That(NHibernateUtil.IsInitialized(dic["ProductLine"]), Is.False);
}
var model = list[0];
Assert.That(((IList<object>) ((IDictionary<string, object>) model["ProductLine"])["Models"]).Contains(model), Is.True);
s.Clear();

await (t.CommitAsync(cancellationToken));
}
}

protected override void OnTearDown()
{
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
s.Delete("from ProductLine");
t.Commit();
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using NHibernate.Cfg;
using NHibernate.Engine;
using Antlr.Runtime.Misc;
using NUnit.Framework;
using NHibernate.Criterion;

Expand All @@ -17,7 +16,7 @@ protected override string MappingsAssembly

protected override IList Mappings
{
get { return new string[] {"EntityModeTest.Map.Basic.ProductLine.hbm.xml"}; }
get { return new[] {"EntityModeTest.Map.Basic.ProductLine.hbm.xml"}; }
}

public delegate IDictionary SingleCarQueryDelegate(ISession session);
Expand Down Expand Up @@ -98,5 +97,84 @@ public void TestLazyDynamicClass(SingleCarQueryDelegate singleCarQueryHandler, A
t.Commit();
}
}

[Test]
public void ShouldWorkWithHQLAndGenerics()
{
TestLazyDynamicClass(
s => s.CreateQuery("from ProductLine pl order by pl.Description").UniqueResult<IDictionary<string, object>>(),
s => s.CreateQuery("from Model m").List<IDictionary<string, object>>());
}

[Test]
public void ShouldWorkWithCriteriaAndGenerics()
{
TestLazyDynamicClass(
s => s.CreateCriteria("ProductLine").AddOrder(Order.Asc("Description")).UniqueResult<IDictionary<string, object>>(),
s => s.CreateCriteria("Model").List<IDictionary<string, object>>());
}

public void TestLazyDynamicClass(
Func<ISession, IDictionary<string, object>> singleCarQueryHandler,
Func<ISession, IList<IDictionary<string, object>>> allModelQueryHandler)
{
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var cars = new Dictionary<string, object> { ["Description"] = "Cars" };

var monaro = new Dictionary<string, object>
{
["ProductLine"] = cars,
["Name"] = "Monaro",
["Description"] = "Holden Monaro"
};

var hsv = new Dictionary<string, object>
{
["ProductLine"] = cars,
["Name"] = "hsv",
["Description"] = "Holden hsv"
};

var models = new List<IDictionary<string, object>> {monaro, hsv};

cars["Models"] = models;

s.Save("ProductLine", cars);
t.Commit();
}

using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
var cars = singleCarQueryHandler(s);
var models = (IList<object>) cars["Models"];
Assert.That(NHibernateUtil.IsInitialized(models), Is.False);
Assert.That(models.Count, Is.EqualTo(2));
Assert.That(NHibernateUtil.IsInitialized(models), Is.True);
s.Clear();
var list = allModelQueryHandler(s);
foreach (var dic in list)
{
Assert.That(NHibernateUtil.IsInitialized(dic["ProductLine"]), Is.False);
}
var model = list[0];
Assert.That(((IList<object>) ((IDictionary<string, object>) model["ProductLine"])["Models"]).Contains(model), Is.True);
s.Clear();

t.Commit();
}
}

protected override void OnTearDown()
{
using (var s = OpenSession())
using (var t = s.BeginTransaction())
{
s.Delete("from ProductLine");
t.Commit();
}
}
}
}
}
3 changes: 3 additions & 0 deletions src/NHibernate/Proxy/Map/MapLazyInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using NHibernate.Engine;

namespace NHibernate.Proxy.Map
Expand All @@ -16,6 +17,8 @@ public IDictionary Map
get { return (IDictionary) GetImplementation(); }
}

public IDictionary<string, object> GenericMap => (IDictionary<string, object>) GetImplementation();

public override System.Type PersistentClass
{
get
Expand Down
70 changes: 69 additions & 1 deletion src/NHibernate/Proxy/Map/MapProxy.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System;
using System.Collections;
using System.Collections.Generic;

namespace NHibernate.Proxy.Map
{
/// <summary> Proxy for "dynamic-map" entity representations. </summary>
[Serializable]
public class MapProxy : INHibernateProxy, IDictionary
public class MapProxy : INHibernateProxy, IDictionary, IDictionary<string, object>
{
private readonly MapLazyInitializer li;

Expand Down Expand Up @@ -114,5 +115,72 @@ public IEnumerator GetEnumerator()
}

#endregion

#region IDictionary<string, object> Members

bool IDictionary<string, object>.ContainsKey(string key)
{
return li.GenericMap.ContainsKey(key);
}

void IDictionary<string, object>.Add(string key, object value)
{
li.GenericMap.Add(key, value);
}

bool IDictionary<string, object>.Remove(string key)
{
return li.GenericMap.Remove(key);
}

bool IDictionary<string, object>.TryGetValue(string key, out object value)
{
return li.GenericMap.TryGetValue(key, out value);
}

object IDictionary<string, object>.this[string key]
{
get => li.GenericMap[key];
set => li.GenericMap[key] = value;
}

ICollection<object> IDictionary<string, object>.Values => li.GenericMap.Values;

ICollection<string> IDictionary<string, object>.Keys => li.GenericMap.Keys;

#endregion

#region ICollection<KeyValuePair<string, object>> Members

void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{
li.GenericMap.Add(item);
}

bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{
return li.GenericMap.Contains(item);
}

void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
li.GenericMap.CopyTo(array, arrayIndex);
}

bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
return li.GenericMap.Remove(item);
}

#endregion

#region IEnumerable<KeyValuePair<string, object>> Members

IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
{
return li.GenericMap.GetEnumerator();
}

#endregion
}
}
Loading