使用反射</t>将EntitySet <t>属性设置为默认值

时间:2010-10-17 05:30:45

标签: c# linq reflection generics

我正在尝试编写用于分离linq类的通用代码。我现在拥有的是:

public void Detach()
{
    this.PropertyChanged = null;
    this.PropertyChanging = null;

    this.Categories = default(EntitySet<Categories>);
    this.Jobs = default(EntitySet<Jobs>);
    this.Tasks= default(EntitySet<Tasks>);
}

这一切都很好,但是我的数据库中有几百个表,并且专门针对每个表执行此操作将是一项耗时的任务。我正在寻找的东西是通用的,我几乎可以用于每个类定义类似于:

public void Detach()
{
    this.PropertyChanged = null;
    this.PropertyChanging = null;

    foreach (System.Reflection.PropertyInfo _prop in this.GetType().GetProperties())
    {
        // if _prop is of type EntitySet<T> then set it to default(EntitySet<T>);
        // TODO: Complete the code here
    }
}

我不确定如何编写代码来执行注释所描述的任务。可以这样做,还是我试图做一些在当前框架中无法完成的事情?

编辑:将EntityRef更改为EntitySet。

1 个答案:

答案 0 :(得分:1)

最简单的方法是通过反射调用.dbml生成的initialize方法:

public void Detach()
{
  GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
} 

为了生成Initialize方法,必须将dbml文件中的Serialization属性设置为“Unidirectional”(右键和选择属性,您将在属性检查器中看到它。)

是的,我感受到了你的痛苦。