开发者

How do you get the DataContext of a LINQ to SQL Entity?

开发者 https://www.devze.com 2023-03-20 11:20 出处:网络
Currently this is what I have: public partial class LinqToSqlEntity { 开发者_如何学C public IQueryable<AnotherLinqToSqlEntity> AnotherLinqToSqlEntities {

Currently this is what I have:

public partial class LinqToSqlEntity {
   开发者_如何学C public IQueryable<AnotherLinqToSqlEntity> AnotherLinqToSqlEntities {
        using(DataContext context = new DataContext) {
            return context.AnotherLinqToSqlEntities.Where(item => item.Property == SOME_VALUE);
        }
    }
}

Is there a way to get the DataContext of this so that I would not need to create a new DataContext?


Sorry, that is not possible. An entity or querable in that case keeps no direct reference of the context.


You can achieve that using the reflection by figuring out if PropertyChanging event was hooked up, but consider this a hack and maybe you can avoid using it with better design. Our use case of this is on detach_EntityName delegate where we change the default Linq behaviour of only deleting the foreign key of a record (setting it to null), with the actual delete from DB.

public static DataContext GetDataContextFromEntityObject(object entity) 
{
    // Use a reflection to get the invocaiton list.
    var o = (PropertyChangingEventHandler)entity.GetType().GetField("PropertyChanging", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(entity);
    var o = GetFieldValue(entity, "PropertyChanging");

    if (o == null) return null;
    var invocationList = o.GetInvocationList();
    if (invocationList != null)
    {
        // DataContext changes are tracked through StandardChangeTracker
        object changeTracker = (from i in invocationList where i.Target.GetType().FullName == "System.Data.Linq.ChangeTracker+StandardChangeTracker" select i.Target).FirstOrDefault();
        if (changeTracker != null)
        {
            object services = GetFieldValue(changeTracker, "services");
            return (DataContext)GetFieldValue(services, "context");
        }
    }

    return null;
}

private static object GetFieldValue(object instance, string propertyName)
{
    return instance.GetType().GetField(propertyName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(instance);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消