我想要实现的是在父实体上使用add-method添加该实体类型的所有子元素的通用方法。必须这样做才能将实体对象“链接”在一起,这样实体框架就可以用数据库密钥(它们都是标识列)来实现“神奇”。
这是我今天使用的那种代码:
EntityObject ParentEntityObject;
EntityObject ChildEntityObject;
((Application)ParentEntityObject).MessageLists.Add((MessageList)ChildEntityObject);
我的程序中有“Application”和“MessageList”作为字符串。因此,我想做两件事:
我不确定如何做到这一点。非常感谢任何建议!
答案 0 :(得分:0)
您可以尝试使用表达式树来执行“神奇”的操作。 例如:
class BaseEntity
{
}
class MessageList : BaseEntity
{
}
class Application:BaseEntity
{
public List<BaseEntity> MessageLists { get; set; }
public Application()
{
MessageLists = new List<BaseEntity>();
}
}
class ExpressionHelper
{
public static Action<object,object> GetMethod(string targetTypename,string targetMemberName,string sourceTypeName)
{
ParameterExpression targetExpression = Expression.Parameter(typeof(object));
MemberExpression propertyExpression = Expression.PropertyOrField(Expression.TypeAs(targetExpression, Type.GetType(targetTypename)), targetMemberName);
ParameterExpression sourceExpression = Expression.Parameter(typeof(object));
Expression callExpression = Expression.Call(propertyExpression, "Add", null, Expression.TypeAs(sourceExpression, Type.GetType(sourceTypeName)));
var lambda = Expression.Lambda<Action<object, object>>(callExpression, targetExpression, sourceExpression);
var method = lambda.Compile();
return method;
}
}
用法:
var app = new Application();
var messageList = new MessageList();
var magicMethod = ExpressionHelper.GetMethod(/*type*/"Application",/*name of Property-Storage*/"MessageLists",/*type of element to store*/"MessageList");
magicMethod(app, messageList);
//now app.MessageLists has one element