How to map list of nested object with Smart
Dear usausa,
I want execute the query to return and can map to object like this:
public class Company
{
public int ID {get;set;}
public string Name {get;set;}
public IList<Staff> Staffs{get;set;}
}
public class Staff
{
public int ID {get;set;}
public string StaffName {get;set;}
}
Please guide me how to implement it
Thanks
Sorry, map to nested objects are not supported now. To create a generic nested mapper, would require designing a specification of where to map DB columns and objects, but I haven't done that yet.
Currently, if you prepare your own IResultMapperFactory, you can use it to handle nested objects. If you want to make your own implementation of IResultMapperFactory, Please refer to the following.
Smart.Data.Accessor/Data/Accessor/Mappers/ObjectResultMapperFactory.cs Smart.Data.Accessor/Data/Accessor/Mappers/SingleResultMapperFactory.cs
Each is a mapper to a standard object and a single value mapper implementation similar to ExecuteScalar.
Oh, I made a mistake. Nest maps cannot be supported with the current interface. You can only create a tuple mapper and nest it on the application side like Dapper's Multi-Mapping.
Tuple map support was added in version 1.2.0.
[Query]
List<ValueTuple<Company, Staff>> Query();
Use it like Dapper's Result Multi-Mapping. https://dapper-tutorial.net/result-multi-mapping
public class ParentEntity
{
public int Id { get; set; }
public string Name { get; set; }
public List<ChildEntity> Children { get; set; }
}
public class ChildEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
accessor.Query().MapOneToMany(p => p.Id, (p, cs) => p.Children = cs)
// Helper
public static class NestedExtensions
{
public static IEnumerable<TP> MapOneToMany<TP, TC, TPKey>(
this IEnumerable<Tuple<TP, TC>> source,
Func<TP, TPKey> parentKeySelector,
Action<TP, List<TC>> combiner)
{
return MapOneToMany(
source,
x => x.Item1,
x => x.Item2,
parentKeySelector,
EqualityComparer<TPKey>.Default,
combiner);
}
public static IEnumerable<TP> MapOneToMany<T, TP, TC, TPKey>(
this IEnumerable<T> source,
Func<T, TP> parentSelector,
Func<T, TC> childSelector,
Func<TP, TPKey> parentKeySelector,
IEqualityComparer<TPKey> keyComparer,
Action<TP, List<TC>> combiner)
{
using (var en = source.GetEnumerator())
{
if (en.MoveNext())
{
var item = en.Current;
var parent = parentSelector(item);
var key = parentKeySelector(parent);
var children = new List<TC>
{
childSelector(item)
};
while (en.MoveNext())
{
var newItem = en.Current;
var newParent = parentSelector(newItem);
var newKey = parentKeySelector(newParent);
if (!keyComparer.Equals(key, newKey))
{
combiner(parent, children);
yield return parent;
key = newKey;
children = new List<TC>();
}
children.Add(childSelector(newItem));
}
combiner(parent, children);
yield return parent;
}
}
}
}