2013-03-26 08:50:18 +01:00
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Linq.Expressions;
|
|
|
|
|
using Marr.Data;
|
|
|
|
|
using Marr.Data.Mapping;
|
|
|
|
|
|
|
|
|
|
namespace NzbDrone.Core.Datastore
|
|
|
|
|
{
|
|
|
|
|
public static class RelationshipExtensions
|
|
|
|
|
{
|
2013-04-29 03:47:06 +02:00
|
|
|
|
public static RelationshipBuilder<TParent> HasOne<TParent, TChild>(this RelationshipBuilder<TParent> relationshipBuilder, Expression<Func<TParent, LazyLoaded<TChild>>> portalExpression, Func<TParent, int> childIdSelector)
|
2013-03-26 08:50:18 +01:00
|
|
|
|
where TParent : ModelBase
|
|
|
|
|
where TChild : ModelBase
|
|
|
|
|
{
|
2013-04-29 03:47:06 +02:00
|
|
|
|
return relationshipBuilder.For(portalExpression.GetMemberName())
|
2013-05-22 07:30:54 +02:00
|
|
|
|
.LazyLoad(
|
|
|
|
|
query: (db, parent) => db.Query<TChild>().SingleOrDefault(c => c.Id == childIdSelector(parent)),
|
|
|
|
|
condition: parent => childIdSelector(parent) > 0
|
|
|
|
|
);
|
2013-03-26 08:50:18 +01:00
|
|
|
|
|
2013-04-29 03:47:06 +02:00
|
|
|
|
}
|
2013-03-26 08:50:18 +01:00
|
|
|
|
|
2013-04-29 03:47:06 +02:00
|
|
|
|
public static RelationshipBuilder<TParent> Relationship<TParent>(this ColumnMapBuilder<TParent> mapBuilder)
|
|
|
|
|
{
|
|
|
|
|
return mapBuilder.Relationships.AutoMapComplexTypeProperties<ILazyLoaded>();
|
2013-03-26 08:50:18 +01:00
|
|
|
|
}
|
|
|
|
|
|
2013-04-29 03:47:06 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static RelationshipBuilder<TParent> HasMany<TParent, TChild>(this RelationshipBuilder<TParent> relationshipBuilder, Expression<Func<TParent, LazyList<TChild>>> portalExpression, Func<TParent, int> childIdSelector)
|
2013-03-26 08:50:18 +01:00
|
|
|
|
where TParent : ModelBase
|
|
|
|
|
where TChild : ModelBase
|
|
|
|
|
{
|
2013-04-29 03:47:06 +02:00
|
|
|
|
return relationshipBuilder.For(portalExpression.GetMemberName())
|
|
|
|
|
.LazyLoad((db, parent) => db.Query<TChild>().Where(c => c.Id == childIdSelector(parent)).ToList());
|
2013-03-26 08:50:18 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
2013-03-26 09:00:46 +01:00
|
|
|
|
|
|
|
|
|
private static string GetMemberName<T, TMember>(this Expression<Func<T, TMember>> member)
|
|
|
|
|
{
|
|
|
|
|
var expression = member.Body as MemberExpression;
|
|
|
|
|
|
|
|
|
|
if (expression == null)
|
|
|
|
|
{
|
|
|
|
|
expression = (MemberExpression)((UnaryExpression)member.Body).Operand;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return expression.Member.Name;
|
|
|
|
|
}
|
2013-03-26 08:50:18 +01:00
|
|
|
|
}
|
|
|
|
|
}
|