Skip to content

Instantly share code, notes, and snippets.

@baralong
Created May 16, 2019 07:28
Show Gist options
  • Save baralong/0538986acc5e25507e691d20c012f17a to your computer and use it in GitHub Desktop.
Save baralong/0538986acc5e25507e691d20c012f17a to your computer and use it in GitHub Desktop.
For a DAL POCO with int IDs link a child to a parent
public static class Extensions
{
public static void Link<TParent, TChild>(this TParent parent, TChild child, Expression<Func<TChild, int>> link)
where TParent : HasId
{
if (parent == null || child == null) return;
if (!(link.Body is MemberExpression member)) return;
var propertyInfo = (PropertyInfo)member.Member;
propertyInfo.SetValue(child, parent.Id);
}
}
// usage
parent.Link(parent.Child, a => a.ParentId);
// this sets the value of parent.Child.ParentId to parent.Id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment