views:

26

answers:

1

I am trying to write generic code for detaching a linq class. What I have currently is:

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

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

This is all fine, however there are several hundred tables in my database and it would be a time consuming task to do this specifically for each and every one of them. What I am looking for is something generic that I can pretty much use for every class definition similar to:

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
    }
}

I am unsure how to write the code to preform the task that is described by the comment. Can this be done or am I trying to do something that just can't be done in the current framework?

Edit: changed EntityRef to EntitySet.

+1  A: 

The easiest way to do this is to call the initialize method generated by your .dbml through reflection:

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

In order for the Initialize method to be generated, you must set the Serialization property in your dbml file to "Unidirectional" (right mouse and select properties, you'll see it in the property inspector).

And yes, I feel your pain.

Rob