How do you get a DataContext LINQ to SQL Entity?

This is currently what I have:

public partial class LinqToSqlEntity { public IQueryable<AnotherLinqToSqlEntity> AnotherLinqToSqlEntities { using(DataContext context = new DataContext) { return context.AnotherLinqToSqlEntities.Where(item => item.Property == SOME_VALUE); } } } 

Is there a way to get a DataContext for this so that I don't have to create a new DataContext?

+4
source share
2 answers

Sorry, this is not possible. The object or request in this case does not contain a direct reference to the context.

+2
source

You can achieve this by using reflection, figuring out if the PropertyChanging event has been connected, but consider how to hack it, and perhaps you can avoid using it with a better design. Our use case is to delegate detach_EntityName, where we change the default Linq behavior only by deleting the foreign record key (setting it to null), with the actual removal from the database.

 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); } 
+1
source

All Articles