繁体   English   中英

设置EntitySet <t> 使用反射默认设置的属性

[英]Setting EntitySet<t> properties to default using reflection

我正在尝试编写用于分离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。

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

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

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

是的,我感到你很痛苦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM