<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6478488875010480037</id><updated>2011-04-21T20:38:44.791-04:00</updated><category term='DataContext'/><category term='LINQ'/><category term='SQL'/><category term='.NET'/><title type='text'>Coding Reflections</title><subtitle type='html'>Random Thoughts and Solutions for Better Software</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://crefs.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://crefs.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Michael Petito</name><uri>http://www.blogger.com/profile/13633541694266265970</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/_Ahq7bY519Zc/ScGSSQAmF8I/AAAAAAAAABo/r-uDjNj29rI/S220/photo.png'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>4</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6478488875010480037.post-3466872276676585231</id><published>2009-03-18T20:02:00.000-04:00</published><updated>2009-03-30T10:19:18.029-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='DataContext'/><category scheme='http://www.blogger.com/atom/ns#' term='.NET'/><category scheme='http://www.blogger.com/atom/ns#' term='SQL'/><category scheme='http://www.blogger.com/atom/ns#' term='LINQ'/><title type='text'>Combining Mapped Database Functions on Multiple DataContexts</title><content type='html'>&lt;p&gt;The LINQ to SQL designer provides some great flexibility for calling scalar and table-valued functions and stored procedures in your database.&amp;#160; You usually just need to drag the function from the Server Explorer into the DBML designer’s method pane and indicate how the output of the function should be materialized.&amp;#160; I’m a fan of keeping as much complex logic out of the database as possible, but sometimes you just can’t efficiently get the data you need from your database through LINQ into your middle tier.&amp;#160; Table-valued functions are especially useful for queries that can’t be expressed easily (or at all) using standard LINQ expressions.&amp;#160; Queries that can be made more efficient using ranking and windowing functions or recursive CTEs are good candidates since they often have no direct translation to LINQ.&amp;#160; Best of all, since the generated methods for table-valued functions return an instance of &lt;em&gt;IQueryable&lt;/em&gt;, you can use function results within more complex LINQ expressions and still have the entire query executed at the database.&lt;/p&gt;  &lt;p&gt;As you have come to expect form LINQ to SQL, pretty much anything you get out of a &lt;em&gt;DataContext&lt;/em&gt; is tied to that &lt;em&gt;DataContext &lt;/em&gt;instance.&amp;#160; This includes any instances of &lt;em&gt;IQueryable&lt;/em&gt; you get from the generated methods for table-valued functions.&amp;#160; In &lt;a href="http://crefs.blogspot.com/2009/03/linq-to-sql-and-repository-pattern.html"&gt;my last post&lt;/a&gt;, I discussed using the LINQ to SQL O/RM behind the repositories in domain-driven design.&amp;#160; In this context, and in many other instances, it can be helpful to maintain just one &lt;em&gt;DataContext&lt;/em&gt; instance for a given thread of execution or “unit of work.”&amp;#160; A singleton instance per thread.&amp;#160; This can be difficult to design, however, if some of your code relies on a particular derived &lt;em&gt;DataContext&lt;/em&gt; type generated by the DBML designer to access its mapped functions.&amp;#160; Worse yet, you might have taken a divide and conquer approach to the database design and used the designer to produce more than one type of derived &lt;em&gt;DataContext.&amp;#160; &lt;/em&gt;These &lt;em&gt;DataContext&lt;/em&gt; classes could exist in separate assemblies and model different entities within the database (for example, maybe you have developed a reusable library for authentication and user management that has its own &lt;em&gt;DataContext &lt;/em&gt;to interact with tables in the database).&lt;/p&gt;  &lt;p&gt;When we look at the code generated for a derived &lt;em&gt;DataContext&lt;/em&gt;, in a simple case we see properties defined for tables:&lt;/p&gt;  &lt;pre class="prettyprint"&gt;public System.Data.Linq.Table&amp;lt;Account&amp;gt; Accounts
{
	get
	{
		return this.GetTable&amp;lt;Account&amp;gt;();
	}
}&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The method GetTable&amp;lt;T&amp;gt; is defined by the &lt;em&gt;DataContext &lt;/em&gt;class, so regardless of the particular &lt;em&gt;DataContext &lt;/em&gt;type you have, it’s clear that we can easily request a table of any entity type.&amp;#160; The table properties generated by the designer are purely a convenience.&amp;#160; If your code is only ever concerned with basic CRUD operations on tables (i.e. you never use mapped database functions), then you should be able to use an appropriately constructed instance of any &lt;em&gt;DataContext, &lt;/em&gt;even the &lt;em&gt;DataContext &lt;/em&gt;class itself, as your singleton &lt;em&gt;DataContext &lt;/em&gt;instance.&lt;/p&gt;

&lt;p&gt;Where you’ll get into trouble is when you need to use a mapped database function.&amp;#160; For now I’m only going to tackle mapped table-valued functions like the one below.&amp;#160; Stored procedures look a little different, but the approach I’m about to discuss can still be applied.&amp;#160; Let’s look at the code that the designer generates for us for a simple mapped function (this mapped function uses a recursive CTE defined in the database to get the ancestors of a particular node in a hierarchy):&lt;/p&gt;

&lt;pre class="prettyprint"&gt;[Function(Name = &amp;quot;dbo.GetNodePath&amp;quot;, IsComposable = true)]
public IQueryable&amp;lt;NodeParent&amp;gt; GetNodePath([Parameter(Name = &amp;quot;NodeID&amp;quot;, DbType = &amp;quot;Int&amp;quot;)] System.Nullable&amp;lt;int&amp;gt; nodeID)
{
    return this.CreateMethodCallQuery&amp;lt;NodeParent&amp;gt;(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), nodeID);
}&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;There isn’t very much going on here.&amp;#160; We have a &lt;em&gt;FunctionAttribute&lt;/em&gt; that tells LINQ to SQL that this is a mapped database function.&amp;#160; It indicates the function name and that it is composable (meaning we can include this in larger LINQ expressions).&amp;#160; The name of the method isn’t really important and the return type is simply whatever you select in the designer (LINQ to SQL tries its best to materialize the result as whatever type you request, or even an auto-generated type).&amp;#160; The parameters to the method are each decorated with a &lt;em&gt;ParameterAttribute &lt;/em&gt;to help translate the method parameters into SQL parameters.&amp;#160; The body of the method calls a method inherited from &lt;em&gt;DataContext &lt;/em&gt;with the current instance, the current method, and each of the parameters passed to the method.&amp;#160; &lt;/p&gt;

&lt;p&gt;The designer generates this code for us within a derived &lt;em&gt;DataContext &lt;/em&gt;type.&amp;#160; Ideally, we’d like to define this mapped function &lt;strong&gt;anywhere&lt;/strong&gt; so that we can use it against any &lt;em&gt;DataContext &lt;/em&gt;instance (especially our singleton instance we’re trying to keep).&lt;/p&gt;

&lt;span class="fullpost"&gt;
&lt;p&gt;Here is the metadata documentation from CreateMethodCallQuery:&lt;/p&gt;

&lt;pre class="prettyprint"&gt;//
// Summary:
//     Executes the table-valued database function associated with the specified
//     CLR method.
//
// Parameters:
//   instance:
//&amp;#160; The instance of the method invocation (the current object).
//
//   methodInfo:
//     Identifies the CLR method that corresponds to a database method.
//
//   parameters:
//     The array of parameters to be passed to the command.
//
// Type parameters:
//   TResult:
//     The type of the elements in the returned collection.
//
// Returns:
//     A collection of resultant values returned by the database query.
protected internal IQueryable&amp;lt;TResult&amp;gt; CreateMethodCallQuery&amp;lt;TResult&amp;gt;(object instance, MethodInfo methodInfo, params object[] parameters);&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;So far so good.&amp;#160; We see that the method is protected internal, so if we want to call this from outside a derived &lt;em&gt;DataContext&lt;/em&gt;, we’re going to have to make a proxy method.&amp;#160; The proxy method would accept the same arguments as CreateMethodCallQuery and simply pass them along to the inherited method.&amp;#160; Here is the first attempt:&lt;/p&gt;

&lt;pre class="prettyprint"&gt;public class DataContextProxy : DataContext
{
    public DataContextProxy(string connectionString) : base(connectionString) { }

    public new IQueryable&amp;lt;TResult&amp;gt; CreateMethodCallQuery&amp;lt;TResult&amp;gt;(object instance, MethodInfo methodInfo, params object[] parameters)
    {
        return base.CreateMethodCallQuery&amp;lt;TResult&amp;gt;(instance, methodInfo, parameters);
    }
}

public class DatabaseFunctions
{
    private DataContextProxy _Proxy;
    public DatabaseFunctions(DataContextProxy proxy) { _Proxy = proxy; }

    [Function(Name = &amp;quot;dbo.GetNodePath&amp;quot;, IsComposable = true)]
    public IQueryable&amp;lt;NodeParent&amp;gt; GetNodePath([Parameter(Name = &amp;quot;NodeID&amp;quot;, DbType = &amp;quot;Int&amp;quot;)] System.Nullable&amp;lt;int&amp;gt; nodeID)
    {
        return _Proxy.CreateMethodCallQuery&amp;lt;NodeParent&amp;gt;(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), nodeID);
    }
}


class Program
{
    static void Main(string[] args)
    {
        using (DataContextProxy dc = new DataContextProxy(Settings.Default.DefaultConnection))
        {
            DatabaseFunctions dbf = new DatabaseFunctions(dc);

            dbf.GetNodePath(0).ToList();    //call the method and force execution by copying to a list
        }
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Again, this is the direction we’re going in: define your mapped functions in a way that allows you to execute them against any &lt;em&gt;DataContext&lt;/em&gt;.&amp;#160; Here our function is defined in a class called &lt;em&gt;DatabaseFunctions&lt;/em&gt;, which receives an instance of our &lt;em&gt;DataContextProxy &lt;/em&gt;class.&lt;/p&gt;

&lt;p&gt;Executing this code produces the following exception:&lt;/p&gt;

&lt;p&gt;System.InvalidOperationException was unhandled
  &lt;br /&gt;&amp;#160; Message=&amp;quot;The method 'GetNodePath' is not mapped as a stored procedure or user-defined function.&amp;quot;

  &lt;br /&gt;&amp;#160; Source=&amp;quot;System.Data.Linq&amp;quot; &lt;/p&gt;

&lt;p&gt;Well, it sure looks like that method is mapped!&amp;#160; Time to break out Reflector!&amp;#160; (Aside: if you’ve ever been curious about how a .NET assembly was implemented, and you’ve never heard of Reflector, &lt;a href="http://www.red-gate.com/products/reflector/" target="_blank"&gt;go download it&lt;/a&gt; right now!)&lt;/p&gt;

&lt;p&gt;We’re using an &lt;em&gt;AttributeMappingSource&lt;/em&gt;, by default, to tell LINQ to SQL how to map our entities and functions to SQL statements.&amp;#160; Derived instances of &lt;em&gt;MappingSource &lt;/em&gt;are responsible for creating an instance of &lt;em&gt;MetaModel&lt;/em&gt; that gives LINQ to SQL this mapping.&amp;#160; There is also an internal class, &lt;em&gt;System.Data.Linq.SqlClient.QueryConverter&lt;/em&gt;, that visits LINQ expressions and helps with the actual translation to SQL.&amp;#160; A quick browse through the disassembled &lt;em&gt;DataContext &lt;/em&gt;and &lt;em&gt;QueryConverter &lt;/em&gt;classes reveals some important facts:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The CreateModel method of any mapping source is intended to examine types derived from &lt;em&gt;DataContext&lt;/em&gt; when building a meta model. &lt;/li&gt;

  &lt;li&gt;The &lt;em&gt;DataContext &lt;/em&gt;class creates a &lt;em&gt;MetaModel &lt;/em&gt;by examining its own type: MetaModel model = mapping.GetModel(base.GetType());. &lt;/li&gt;

  &lt;li&gt;The &lt;em&gt;QueryConverter&lt;/em&gt; VisitMethodCall method will only proceed to VisitMappedFunctionCall if the method is an instance method defined on a class derived from &lt;em&gt;DataContext&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Our mapped function isn’t defined on a class derived from &lt;em&gt;DataContext, &lt;/em&gt;so the &lt;em&gt;QueryConverter &lt;/em&gt;won’t treat it as a mapped function.&amp;#160; However, we don’t even get to that point yet since our mapped function is defined outside of the &lt;em&gt;DataContextProxy &lt;/em&gt;class and the &lt;em&gt;AttributedMetaModel&lt;/em&gt; isn’t aware of it.&amp;#160; To take care of both, we’ll have &lt;em&gt;DatabaseFunctions &lt;/em&gt;subclass &lt;em&gt;DataContext &lt;/em&gt;and we’ll define our own &lt;em&gt;MappingSource &lt;/em&gt;and &lt;em&gt;MetaModel &lt;/em&gt;classes that dynamically build models as necessary based on the reflected type of the &lt;em&gt;MethodInfo&lt;/em&gt; passed to CreateMethodCallQuery.&amp;#160; First, the &lt;em&gt;DynamicAttributeMappingSource&lt;/em&gt;:&lt;/p&gt;

&lt;pre class="prettyprint"&gt;internal class DynamicAttributeMappingSource : MappingSource
{
    private static AttributeMappingSource AttributeMapping = new AttributeMappingSource();

    private Dictionary&amp;lt;Type, MetaModel&amp;gt; _ModelDictionary = new Dictionary&amp;lt;Type, MetaModel&amp;gt;();
    private ReaderWriterLockSlim _ModelLock = new ReaderWriterLockSlim();

    public MetaModel Primary { get { return GetModel(typeof(DataContextProxy)); } }

    protected override MetaModel CreateModel(Type dataContextType)
    {
        MetaModel Result;

        _ModelLock.EnterReadLock();
        try
        {
            if (_ModelDictionary.TryGetValue(dataContextType, out Result))
                return Result;
        }
        finally
        {
            _ModelLock.ExitReadLock();
        }

        _ModelLock.EnterWriteLock();
        try
        {
            if (_ModelDictionary.TryGetValue(dataContextType, out Result))
                return Result;

            Result = new DynamicAttributedMetaModel(this, AttributeMapping.GetModel(dataContextType));
            _ModelDictionary.Add(dataContextType, Result);
        }
        finally
        {
            _ModelLock.ExitWriteLock();
        }

        return Result;
    }
}&lt;/pre&gt;

&lt;p&gt;There’s nothing fancy really going on here.&amp;#160; A dictionary keeps track of models we’ve created for particular types and, in CreateModel, we have some thread-safe code for creating a model: we either get it out of the dictionary, or create a new one and put it into the dictionary.&amp;#160; When we create our &lt;em&gt;MetaModel &lt;/em&gt;instances, we give them a &lt;em&gt;MetaModel &lt;/em&gt;generated by an &lt;em&gt;AttributeMappingSource &lt;/em&gt;as a starting point.&amp;#160; Here is the &lt;em&gt;DynamicAttributedMetaModel&lt;/em&gt;:&lt;/p&gt;

&lt;pre class="prettyprint"&gt;internal class DynamicAttributedMetaModel : MetaModel
{
    public DynamicAttributeMappingSource DynamicSource { get; private set; }
    public MetaModel Surrogate { get; private set; }

    public DynamicAttributedMetaModel(DynamicAttributeMappingSource dynamicSource, MetaModel surrogate)
    {
        DynamicSource = dynamicSource;
        Surrogate = surrogate;
    }

    public override Type ContextType
    {
        get { return Surrogate.ContextType; }
    }

    public override string DatabaseName
    {
        get { return Surrogate.DatabaseName; }
    }

    public override MetaFunction GetFunction(System.Reflection.MethodInfo method)
    {
        Type MethodType = method.ReflectedType;

        if (Surrogate.ContextType == MethodType)
            return Surrogate.GetFunction(method);
        else
            return DynamicSource.GetModel(MethodType).GetFunction(method);
    }

    public override IEnumerable&amp;lt;MetaFunction&amp;gt; GetFunctions()
    {
        return Surrogate.GetFunctions();
    }

    public override MetaType GetMetaType(Type type)
    {
        return Surrogate.GetMetaType(type);
    }

    public override MetaTable GetTable(Type rowType)
    {
        return Surrogate.GetTable(rowType);
    }

    public override IEnumerable&amp;lt;MetaTable&amp;gt; GetTables()
    {
        return Surrogate.GetTables();
    }

    public override MappingSource MappingSource
    {
        get { return DynamicSource; }
    }

    public override Type ProviderType
    {
        get { return Surrogate.ProviderType; }
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;This class is a proxy for a &lt;em&gt;MetaModel, &lt;/em&gt;passing calls along to the surrogate model.&amp;#160; The MappingSource property refers back to the &lt;em&gt;DynamicAttributeMappingSource &lt;/em&gt;(since that is in fact our mapping source), and there is some extra logic in the GetFunction method.&amp;#160; When the mapping for a function is requested, we check to see if the method is defined on a type that matches our model’s type.&amp;#160; If it is, then it has already been mapped and we can easily get the &lt;em&gt;MetaFunction &lt;/em&gt;instance describing that mapped function from our surrogate model.&amp;#160; Otherwise, we have to get the &lt;em&gt;MetaModel &lt;/em&gt;corresponding to the method’s type.&amp;#160; Our (dynamic) &lt;em&gt;MappingSource&lt;/em&gt; can provide that for us easily.&lt;/p&gt;

&lt;p&gt;Let’s change our &lt;em&gt;DataContextProxy &lt;/em&gt;to use our new mapping source by default.&amp;#160; &lt;em&gt;MappingSource &lt;/em&gt;instances provided here and by the framework are thread-safe.&amp;#160; This allows us to use one static instance and avoid the overhead of using reflection to re-build our &lt;em&gt;MetaModel&lt;/em&gt; instances every time we create a new &lt;em&gt;DataContext &lt;/em&gt;(the &lt;em&gt;MappingSource &lt;/em&gt;class even implements caching of models in much the same way the above code does).&lt;/p&gt;

&lt;pre class="prettyprint"&gt;private static MappingSource _Mapping = new DynamicAttributeMappingSource();

public DataContextProxy(string connectionString) : base(connectionString, _Mapping) { }&lt;/pre&gt;

&lt;p&gt;And for our &lt;em&gt;DatabaseFunctions&lt;/em&gt; class:&lt;/p&gt;

&lt;pre class="prettyprint"&gt;public class DatabaseFunctions : DataContext
{
    public DatabaseFunctions(DataContextProxy proxy) : base(string.Empty) { _Proxy = proxy; }&lt;/pre&gt;

&lt;pre class="prettyprint"&gt;…&lt;/pre&gt;

&lt;pre class="prettyprint"&gt;}&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Okay let’s give it a go with the same driver code as before!&lt;/p&gt;

&lt;p&gt;System.InvalidOperationException was unhandled
  &lt;br /&gt;&amp;#160; Message=&amp;quot;The query contains references to items defined on a different data context.&amp;quot;

  &lt;br /&gt;&amp;#160; Source=&amp;quot;System.Data.Linq&amp;quot; &lt;/p&gt;

&lt;p&gt;Well I suppose we should have expected this.&amp;#160; We have two &lt;em&gt;DataContext &lt;/em&gt;types now: &lt;em&gt;DataContextProxy &lt;/em&gt;and &lt;em&gt;DatabaseFunctions&lt;/em&gt;.&amp;#160; The stack trace for the exception reveals that the check is made by the &lt;em&gt;QueryConverter &lt;/em&gt;class: &lt;/p&gt;

&lt;pre class="prettyprint"&gt;private SqlNode VisitMappedFunctionCall(MethodCallExpression mc)
{
    MetaFunction function = this.services.Model.GetFunction(mc.Method);
    this.CheckContext(this.VisitExpression(mc.Object));
    if (!function.IsComposable)
    {
        return this.TranslateStoredProcedureCall(mc, function);
    }
    if (function.ResultRowTypes.Count &amp;gt; 0)
    {
        return this.TranslateTableValuedFunction(mc, function);
    }
    ProviderType sqlType = ((function.ReturnParameter != null) &amp;amp;&amp;amp; !string.IsNullOrEmpty(function.ReturnParameter.DbType)) ? this.typeProvider.Parse(function.ReturnParameter.DbType) : this.typeProvider.From(mc.Method.ReturnType);
    List&amp;lt;SqlExpression&amp;gt; functionParameters = this.GetFunctionParameters(mc, function);
    return this.sql.FunctionCall(mc.Method.ReturnType, sqlType, function.MappedName, functionParameters, mc);
}

private void CheckContext(SqlExpression expr)
{
    SqlValue value2 = expr as SqlValue;
    if (value2 != null)
    {
        DataContext context = value2.Value as DataContext;
        if ((context != null) &amp;amp;&amp;amp; (context != this.services.Context))
        {
            throw Error.WrongDataContext();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;OK, let’s think here.&amp;#160; What is the &lt;em&gt;QueryConverter &lt;/em&gt;actually working with?&amp;#160; It’s trying to translate an expression tree associated with an &lt;em&gt;IQueryable&lt;/em&gt; object into an SQL statement.&amp;#160; The expression tree isn’t being executed, it’s just being parsed.&amp;#160; We need an instance of an object to execute an instance method on that object, but there’s no reason we can’t have an expression tree that represents calling such a method on a null reference.&amp;#160; If I can convince the &lt;em&gt;QueryConverter &lt;/em&gt;that the context variable is null, then the CheckContext method will return successfully!&amp;#160; The context variable is the instance of the derived &lt;em&gt;DataContext&lt;/em&gt; that was used to call our mapped function.&amp;#160; In our case, this is an instance of the class &lt;em&gt;DatabaseFunctions&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;So where is this part of the expression tree generated?&amp;#160; By the &lt;em&gt;DataContext, &lt;/em&gt;of course:&lt;/p&gt;

&lt;pre class="prettyprint"&gt;protected internal IQueryable&amp;lt;TResult&amp;gt; CreateMethodCallQuery&amp;lt;TResult&amp;gt;(object instance, MethodInfo methodInfo, params object[] parameters)
{
    this.CheckDispose();
    if (instance == null)
    {
        throw Error.ArgumentNull(&amp;quot;instance&amp;quot;);
    }
    if (methodInfo == null)
    {
        throw Error.ArgumentNull(&amp;quot;methodInfo&amp;quot;);
    }
    if (parameters == null)
    {
        throw Error.ArgumentNull(&amp;quot;parameters&amp;quot;);
    }
    if (!typeof(IQueryable&amp;lt;TResult&amp;gt;).IsAssignableFrom(methodInfo.ReturnType))
    {
        throw Error.ExpectedQueryableArgument(&amp;quot;methodInfo&amp;quot;, typeof(IQueryable&amp;lt;TResult&amp;gt;));
    }
    return new DataQuery&amp;lt;TResult&amp;gt;(this, this.GetMethodCall(instance, methodInfo, parameters));
}&lt;/pre&gt;

&lt;pre class="prettyprint"&gt;private Expression GetMethodCall(object instance, MethodInfo methodInfo, params object[] parameters)
{
    this.CheckDispose();
    if (parameters.Length &amp;lt;= 0)
    {
        return Expression.Call(Expression.Constant(instance), methodInfo);
    }
    ParameterInfo[] infoArray = methodInfo.GetParameters();
    List&amp;lt;Expression&amp;gt; arguments = new List&amp;lt;Expression&amp;gt;(parameters.Length);
    int index = 0;
    int length = parameters.Length;
    while (index &amp;lt; length)
    {
        Type parameterType = infoArray[index].ParameterType;
        if (parameterType.IsByRef)
        {
            parameterType = parameterType.GetElementType();
        }
        arguments.Add(Expression.Constant(parameters[index], parameterType));
        index++;
    }
    return Expression.Call(Expression.Constant(instance), methodInfo, arguments);
}&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The GetMethodCall method is responsible for generating the expression tree, which always uses the instance passed to CreateMethodCallQuery in Expression.Call(…).&amp;#160; We can’t pass an instance of any type other than a type that declares our mapped function to CreateMethodCallQuery, since Expression.Call verifies that the instance type supports the specified method.&lt;/p&gt;

&lt;p&gt;To circumvent this, we need to use our own GetMethodCall method and construct an instance of the &lt;em&gt;DataQuery &lt;/em&gt;class (which is internal, unfortunately).&lt;/p&gt;

&lt;p&gt;Here is the completed &lt;em&gt;DataContextProxy&lt;/em&gt; class:&lt;/p&gt;

&lt;pre class="prettyprint"&gt;public class DataContextProxy : DataContext
{
    private static MappingSource _Mapping = new DynamicAttributeMappingSource();

    private static bool _ReflectionInit = false;
    private static ReaderWriterLockSlim _ReflectionLock = new ReaderWriterLockSlim();
    private static Type _DataQueryType;
    private static FieldInfo _DataContextProviderMember;
    private static MethodInfo _IProviderExecuteMethod;

    /// &amp;lt;summary&amp;gt;
    /// Construct a new instance of the data context proxy using a provided connection string and dynamic attribute mapping.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;connectionString&amp;quot;&amp;gt;The connection string used to connect to the underlying database.&amp;lt;/param&amp;gt;
    public DataContextProxy(string connectionString)
        : base(connectionString, _Mapping)
    {
    }

    #region Proxy Methods for Cross-Context Calls

    private static void InitReflection()
    {
        _ReflectionLock.EnterReadLock();
        try
        {
            if (_ReflectionInit)
                return;
        }
        finally
        {
            _ReflectionLock.ExitReadLock();
        }

        _ReflectionLock.EnterWriteLock();
        try
        {
            if (_ReflectionInit)
                return;

            _DataQueryType = typeof(DataContext).Assembly.GetType(&amp;quot;System.Data.Linq.DataQuery`1&amp;quot;, true);
            _DataContextProviderMember = typeof(DataContext).GetField(&amp;quot;provider&amp;quot;, BindingFlags.Instance | BindingFlags.NonPublic);
            _IProviderExecuteMethod = typeof(DataContext).Assembly.GetType(&amp;quot;System.Data.Linq.Provider.IProvider&amp;quot;).GetMethod(&amp;quot;Execute&amp;quot;);

            _ReflectionInit = true;
        }
        finally
        {
            _ReflectionLock.ExitWriteLock();
        }
    }

    /// &amp;lt;summary&amp;gt;
    /// Uses the mapping attributes on a method definition to execute a stored procedure.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;instance&amp;quot;&amp;gt;The instance of the class that exposes the method.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;method&amp;quot;&amp;gt;The method invoked.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;parameters&amp;quot;&amp;gt;The parameters to the method invoked.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;The execution result.&amp;lt;/returns&amp;gt;
    public IExecuteResult ExecuteMethodCall(DataContext instance, MethodInfo method, params object[] parameters)
    {
        InitReflection();

        object Provider = _DataContextProviderMember.GetValue(this);
        return (IExecuteResult)_IProviderExecuteMethod.Invoke(Provider, new object[] { GetMethodCall(instance, method, parameters) });
    }

    /// &amp;lt;summary&amp;gt;
    /// Uses the mapping attributes on a method definition to query a table-valued function.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;typeparam name=&amp;quot;TElement&amp;quot;&amp;gt;The type of element queried.&amp;lt;/typeparam&amp;gt;
    /// &amp;lt;param name=&amp;quot;instance&amp;quot;&amp;gt;The instance of the class that exposes the method.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;method&amp;quot;&amp;gt;The method invoked.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;parameters&amp;quot;&amp;gt;The parameters to the method invoked.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;The queryable result.&amp;lt;/returns&amp;gt;
    public IQueryable&amp;lt;TElement&amp;gt; CreateMethodCallQuery&amp;lt;TElement&amp;gt;(DataContext instance, MethodInfo method, params object[] parameters)
    {
        InitReflection();

        Type DataQueryType = _DataQueryType.MakeGenericType(typeof(TElement));

        return (IQueryable&amp;lt;TElement&amp;gt;)Activator.CreateInstance(DataQueryType, this, GetMethodCall(instance, method, parameters));
    }

    /// &amp;lt;remarks&amp;gt;This is copied almost verbatim from System.DataLinq.DataContext:GetMethodCall.
    /// However, note that the instance is null but of the correct type.
    /// This exploits two loop-holes in System.Data.Linq.SqlClient.QueryConverter:
    /// (1) An instance inheriting DataContext is required to map functions, and
    /// (2) A null instance passes the CheckContext method by default.&amp;lt;/remarks&amp;gt;
    private static Expression GetMethodCall(DataContext instance, MethodInfo methodInfo, params object[] parameters)
    {
        if (parameters.Length &amp;lt;= 0)
        {
            return Expression.Call(Expression.Constant(null, methodInfo.DeclaringType), methodInfo);
        }
        ParameterInfo[] infoArray = methodInfo.GetParameters();
        List&amp;lt;Expression&amp;gt; arguments = new List&amp;lt;Expression&amp;gt;(parameters.Length);
        int index = 0;
        int length = parameters.Length;
        while (index &amp;lt; length)
        {
            Type parameterType = infoArray[index].ParameterType;
            if (parameterType.IsByRef)
            {
                parameterType = parameterType.GetElementType();
            }
            arguments.Add(Expression.Constant(parameters[index], parameterType));
            index++;
        }
        return Expression.Call(Expression.Constant(null, methodInfo.DeclaringType), methodInfo, arguments);
    }

    #endregion
}&lt;/pre&gt;


&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Notice how GetMethodCall passes null and a type to Expression.Constant, instead of the instance parameter.&amp;#160; This circumvents the context type check performed by &lt;em&gt;QueryConverter&lt;/em&gt;.&amp;#160; We also have to use reflection to dig into some of the internal classes used by &lt;em&gt;DataContext&lt;/em&gt;.&amp;#160; Obviously if LINQ to SQL changes significantly, this may not work anymore (but hopefully they’ll have added this or similar functionality in).&lt;/p&gt;

&lt;p&gt;The above code includes both the CreateMethodCallQuery method to handle table-valued functions and the ExecuteMethodCall method to handle stored procedures.&amp;#160; Using either method appropriately, you can now define your mapped database functions outside of the designer generated code and use them against any data context!&lt;/p&gt;
&lt;/span&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6478488875010480037-3466872276676585231?l=crefs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://crefs.blogspot.com/feeds/3466872276676585231/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6478488875010480037&amp;postID=3466872276676585231' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/3466872276676585231'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/3466872276676585231'/><link rel='alternate' type='text/html' href='http://crefs.blogspot.com/2009/03/combining-mapped-database-functions-on.html' title='Combining Mapped Database Functions on Multiple DataContexts'/><author><name>Michael Petito</name><uri>http://www.blogger.com/profile/13633541694266265970</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/_Ahq7bY519Zc/ScGSSQAmF8I/AAAAAAAAABo/r-uDjNj29rI/S220/photo.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6478488875010480037.post-7303473569791858948</id><published>2009-03-18T15:07:00.001-04:00</published><updated>2009-03-18T20:40:53.859-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='DataContext'/><category scheme='http://www.blogger.com/atom/ns#' term='.NET'/><category scheme='http://www.blogger.com/atom/ns#' term='SQL'/><category scheme='http://www.blogger.com/atom/ns#' term='LINQ'/><title type='text'>LINQ to SQL and the Repository Pattern</title><content type='html'>&lt;p&gt;So it has been a while since I’ve blogged about anything, and for that I do apologize!&amp;#160; Things have been pretty busy around here, which I suppose should be considered a good thing!&lt;/p&gt;  &lt;p&gt;Recently I’ve been working with &lt;a href="http://en.wikipedia.org/wiki/Domain-driven_design"&gt;domain-driven design&lt;/a&gt; and trying to get a feel for how LINQ to SQL can be utilized as the O/R mapper behind repositories.&amp;#160; In DDD, you usually have a repository for each domain entity to handle CRUD operations.&amp;#160; With LINQ, your repository can expose instances of &lt;em&gt;IQueryable&amp;lt;T&amp;gt; &lt;/em&gt;so that client code can efficiently execute complex queries on the domain using LINQ.&amp;#160; LINQ to SQL does a great job translating this to SQL and materializing the results.&amp;#160; Wonderful!&amp;#160; And if you’re really picky about DDD, you can even &lt;a href="http://www.iridescence.no/post/Linq-to-Sql-Programming-Against-an-Interface-and-the-Repository-Pattern.aspx"&gt;define a separate interface for your entities&lt;/a&gt; within your domain model and avoid exposing designer generated classes outside of your repositories.&lt;/p&gt;  &lt;p&gt;One problem with the repository approach is managing the life cycle of the &lt;em&gt;DataContext&lt;/em&gt; object.&amp;#160; If you have ever used LINQ to SQL, you’ve run into one problem or another with the &lt;em&gt;DataContext &lt;/em&gt;class.&amp;#160; Typically users run into one of the following problems:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You cannot use more than one instance of a &lt;em&gt;DataContext&lt;/em&gt; in a single LINQ query, and &lt;/li&gt;    &lt;li&gt;You cannot use objects materialized by one &lt;em&gt;DataContext &lt;/em&gt;in a new &lt;em&gt;DataContext &lt;/em&gt;instance. &lt;/li&gt; &lt;/ul&gt; &lt;span class="fullpost"&gt;   &lt;p&gt;So both problems can only happen if you have more than one instance of a &lt;em&gt;DataContext &lt;/em&gt;floating around.&amp;#160; Why might that be?&amp;#160; Well, unless you constantly provide method parameters to pas around a single &lt;em&gt;DataContext &lt;/em&gt;instance, it’s going to be really hard to encapsulate any common functionality anywhere!&amp;#160; Here’s an example:&lt;/p&gt;    &lt;pre class="prettyprint"&gt;public IQueryable&amp;lt;Account&amp;gt; ListAccountsByLastName(string name)
{
    //we would normally do: using(DataContext dc...) but we can't, because then the DataContext would be disposed before returning our query.
    DataContext dc = new DataContext(Properties.Settings.Default.ConnectionString);
    return (from a in dc.GetTable&amp;lt;Account&amp;gt;()
            where a.LastName.Contains(name)
            select a);
}

public IQueryable&amp;lt;Account&amp;gt; ListAccountsByLastName(DataContext dc, string name)
{
    return (from a in dc.GetTable&amp;lt;Account&amp;gt;()
            where a.LastName.Contains(name)
            select a);
}&lt;/pre&gt;

  &lt;p&gt;&lt;/p&gt;

  &lt;p&gt;The first method has to come up with its own &lt;em&gt;DataContext&lt;/em&gt;.&amp;#160; The second method accepts a &lt;em&gt;DataContext &lt;/em&gt;as the first parameter.&amp;#160; Neither method is good: you either introduce a new &lt;em&gt;DataContext&lt;/em&gt; and limit what can be accomplished with the instance &lt;em&gt;IQueryable&amp;lt;T&amp;gt; &lt;/em&gt;and any materialized results, or you always have to be concerned with passing around a &lt;em&gt;DataContext&lt;/em&gt;.&lt;/p&gt;

  &lt;p&gt;I’ve already discussed the second problem with a &lt;a href="http://crefs.blogspot.com/2008/08/detaching-linq-to-sql-entities.html"&gt;possible workaround&lt;/a&gt;.&lt;/p&gt;

  &lt;p&gt;I don’t know what the LINQ to SQL developers were thinking.&amp;#160; They obviously didn’t take a lesson from the ADO.NET and System.Transactions developers.&amp;#160; In my mind, the &lt;em&gt;DataContext &lt;/em&gt;class should be available as part of an &lt;a href="http://www.dotnetlog.com/archive/2008/03/18/best-practice-and-effective-way-of-using-datacontext-in-linq.aspx"&gt;ambient scope&lt;/a&gt;, just like &lt;em&gt;System.Transactions.TransactionScope.&amp;#160; &lt;/em&gt;You should always be able to pick up the current &lt;em&gt;DataContext.&amp;#160; &lt;/em&gt;We can easily shield client code from any details required when handling the &lt;em&gt;DataContext &lt;/em&gt;class by wrapping it up in a &lt;em&gt;UnitOfWork &lt;/em&gt;class.&amp;#160; The result: a clean separation of client code from the O/R mapper used by the repositories.&lt;/p&gt;

  &lt;p&gt;Here’s some sample code:&lt;/p&gt;

  &lt;pre class="prettyprint"&gt;public Account CreateUser(string email, string firstName, string lastName)
{
    IUserRepository Users = IoC.ResolveService&amp;lt;IUserRepository&amp;gt;();

    Account NewUser = Users.CreateUser(email);

    NewUser.FirstName = firstName;
    NewUser.LastName = lastName;

    return NewUser;
}

public void Main()
{
    using (IUnitOfWork Work = UnitOfWork.Start())
    {
        CreateUser(&amp;quot;someone@somewhere.com&amp;quot;, &amp;quot;Michael&amp;quot;, &amp;quot;P.&amp;quot;);

        Work.Commit();
    }
}&lt;/pre&gt;

  &lt;p&gt;&lt;/p&gt;

  &lt;p&gt;Here we see both the Unit of Work and Inversion of Control patterns at work.&amp;#160; A Unit of Work is simply an ambient context within which code executes.&amp;#160; My implementation simply provides a dictionary for storing objects within that thread-specific context.&amp;#160; It also supports a Commit operation that completes any transacted operations performed in the context.&amp;#160; The Inversion of Control pattern allows me to define the repository that implements the &lt;em&gt;IUserRepository&lt;/em&gt; interface somewhere other than in the client code.&amp;#160; This implementation uses a section in the app.config file.&lt;/p&gt;

  &lt;p&gt;So within the CreateUser method above, we get an instance of the user repository and invoke its CreateUser method.&amp;#160; Here’s that method:&lt;/p&gt;

  &lt;pre class="prettyprint"&gt;public Account CreateUser(string email)
{
    Account TargetAccount = new Account()
    {
        Type = AccountType.Standard,
        Email = email,
    };

    Context.GetTable&amp;lt;Account&amp;gt;().InsertOnSubmit(TargetAccount);

    return TargetAccount;
}&lt;/pre&gt;

  &lt;p&gt;Notice how there is no explicit creation of a &lt;em&gt;DataContext &lt;/em&gt;even within the repository.&amp;#160; The Context property is exposed by a repository base class:&lt;/p&gt;

  &lt;pre class="prettyprint"&gt;protected DataContext Context { get { return DataContextProxy.Singleton; } }&lt;/pre&gt;

  &lt;p&gt;The &lt;em&gt;DataContextProxy &lt;/em&gt;class and Singleton property just help us manage a single instance of a &lt;em&gt;DataContext &lt;/em&gt;stored in the current unit of work scope (an exception is raised if a unit of work hasn’t been started by the client code).&amp;#160; The inversion of control pattern is actually used again by the &lt;em&gt;DataContextProxy&lt;/em&gt; class to delegate creation of the &lt;em&gt;DataContext &lt;/em&gt;instance.&amp;#160; This allows the connection string (and optionally a mapping source) to be provided by client code.&lt;/p&gt;

  &lt;p&gt;By limiting the instances of &lt;em&gt;DataContext &lt;/em&gt;to just one, within a unit of work scope, you never need to worry about which &lt;em&gt;DataContext &lt;/em&gt;materialized a particular object or produced an instance of &lt;em&gt;IQueryable&amp;lt;T&amp;gt;&lt;/em&gt;.&amp;#160; Your repositories always have access to the current &lt;em&gt;DataContext &lt;/em&gt;and your client code never has to worry about it or any complex attaching / detaching behavior.&lt;/p&gt;

  &lt;p&gt;Excellent!&amp;#160; But you might be wondering: what do I do if I use stored procedures and table valued functions that have been generated by the LINQ to SQL designer for my particular data context.&amp;#160; My repository only has access to plain old &lt;em&gt;DataContext &lt;/em&gt;and the GetTable&amp;lt;T&amp;gt; method&lt;em&gt;.&amp;#160; &lt;/em&gt;Well, you could execute your database functions using the &lt;em&gt;DataContext &lt;/em&gt;method ExecuteQuery.&amp;#160; This will work, but you’ll get back an IEnumerable&amp;lt;T&amp;gt; instance for table value functions, not an IQueryable&amp;lt;T&amp;gt; instance.&amp;#160; This means any further LINQ statements will be done in memory, not executed in SQL.&lt;/p&gt;

  &lt;p&gt;You could also use your own derived &lt;em&gt;DataContext &lt;/em&gt;generated by the designer to call your database functions, but then you’d be subject to the limitations above when working with multiple &lt;em&gt;DataContext &lt;/em&gt;instances.&amp;#160; At least, you should be.&amp;#160; In reality there is a loophole in the LINQ to SQL query converter that &lt;em&gt;does &lt;/em&gt;allow you to successfully combine queries involving mapped database functions from different contexts.&amp;#160; You don’t get this functionality automatically, but I’ll show you the rest of the &lt;em&gt;DataContextProxy &lt;/em&gt;class and how it bypasses the &lt;em&gt;DataContext &lt;/em&gt;method CreateMethodCallQuery next time!&lt;/p&gt;
&lt;/span&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6478488875010480037-7303473569791858948?l=crefs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://crefs.blogspot.com/feeds/7303473569791858948/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6478488875010480037&amp;postID=7303473569791858948' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/7303473569791858948'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/7303473569791858948'/><link rel='alternate' type='text/html' href='http://crefs.blogspot.com/2009/03/linq-to-sql-and-repository-pattern.html' title='LINQ to SQL and the Repository Pattern'/><author><name>Michael Petito</name><uri>http://www.blogger.com/profile/13633541694266265970</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/_Ahq7bY519Zc/ScGSSQAmF8I/AAAAAAAAABo/r-uDjNj29rI/S220/photo.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6478488875010480037.post-885274682935427859</id><published>2008-08-24T17:30:00.015-04:00</published><updated>2009-03-18T09:22:02.192-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='DataContext'/><category scheme='http://www.blogger.com/atom/ns#' term='.NET'/><category scheme='http://www.blogger.com/atom/ns#' term='SQL'/><category scheme='http://www.blogger.com/atom/ns#' term='LINQ'/><title type='text'>Detaching LINQ to SQL Entities</title><content type='html'>&lt;p&gt;
    I've been playing around with the LINQ to SQL framework in .NET 3.5 for mapping
    classes to a SQL database. Exposing your data model through LINQ-able classes gives
    you the ability to write strongly typed queries in your code that are later translated
    to the necessary SQL commands. The framework materializes query results into objects
    for you, and provides methods for inserting, updating and deleting data. For a nice
    quick overview, I suggest checking out the &lt;a href="http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx"&gt;
        LINQ to SQL - 5 Minute Overview&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
    One issue that I keep seeing with the &lt;i&gt;DataContext &lt;/i&gt;class in this framework
    is the ability to use entities materialized in one context within another context.
&lt;/p&gt;
&lt;span class="fullpost"&gt;
&lt;p&gt;
    Consider a simple application that supports logging a user in and having users post
    content.
&lt;/p&gt;
&lt;pre class="prettyprint"&gt;//a static login method for the Account class
public static Account Login(string email, string password)
{
    using (CommunityDataContext dc = new CommunityDataContext())
    {
        //lookup the account
        Account ExistingAccount = (from a in dc.Accounts
                                  where a.Email == email
                                  select a).FirstOrDefault();

        if (ExistingAccount == null //username not found
           || ExistingAccount.Password != password)    //password doesn't match
            return null;

        //update the last seen timestamp
        ExistingAccount.LastSeen = DateTime.UtcNow;
        dc.SubmitChanges();

        return ExistingAccount;
    }
}

//some driver code
Account User = Account.Login("someone@somewhere.com", "password");
if (User == null)
throw new Exception("Login Failed.");

using (CommunityDataContext dc = new CommunityDataContext())
{
    Post NewPost = new Post()
    {
        Account = User,
        Content = "Test Content"
    };

    dc.Posts.InsertOnSubmit(NewPost);
    dc.SubmitChanges();
}
&lt;/pre&gt;
&lt;p&gt;
    If we run this code, we'll find that an insert is attempted. What is being inserted
    might surprise you! Here is the log output from the &lt;i&gt;DataContext&lt;/i&gt;:
&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
DECLARE @output TABLE([AccountID] UniqueIdentifier)
DECLARE @id UniqueIdentifier
INSERT INTO [dbo].[Account]([Email], [Password], [LastSeen])
OUTPUT INSERTED.[AccountID] INTO @output
VALUES (@p0, @p1, @p2)
SELECT @id = AccountID FROM @output

SELECT [t0].[AccountID], [t0].[Created]
FROM [dbo].[Account] AS [t0]
WHERE [t0].[AccountID] = (@id)
-- @p0: Input VarChar (Size = 21; Prec = 0; Scale = 0) [someone@somewhere.com]
-- @p1: Input VarChar (Size = 8; Prec = 0; Scale = 0) [password]
-- @p2: Input SmallDateTime (Size = 0; Prec = 0; Scale = 0) [8/24/2008 8:09:35 PM]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30428.1
&lt;/pre&gt;
&lt;p&gt;
    You can see that we are trying to insert an &lt;i&gt;Account &lt;/i&gt;instance, specifically
    the one I logged in as! Execution is haulted at this point within my code as an
    exception is raised (I have created a unique key constraint for account email addresses).
&lt;/p&gt;
&lt;p&gt;
    The issue is that the &lt;i&gt;DataContext&lt;/i&gt; is treating the &lt;i&gt;Account &lt;/i&gt;instance
    as a new account and attempting to insert it before inserting the new &lt;i&gt;Post&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
    To prevent this behavior, inevitably the Attach method comes up. We might decide
    to try the following:
&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
using (CommunityDataContext dc = new CommunityDataContext())
{
    dc.Accounts.Attach(User);
    Post NewPost = new Post()...
&lt;/pre&gt;
&lt;p&gt;
    And now we reach the crux of our problem. The call to Attach raises a &lt;i&gt;NotSupportException&lt;/i&gt;:
    An attempt has been made to Attach or Add an entity that is not new, perhaps having
    been loaded from another DataContext. This is not supported.
&lt;/p&gt;
&lt;p&gt;
    So there are many solutions that I've read about, just try searching &lt;a href="http://www.google.com/search?q=linq+to+sql+attach+detach"&gt;
        Google&lt;/a&gt;. They range from:&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;Passing your &lt;i&gt;DataContext&lt;/i&gt; instance to each of your methods so that a single
        instance is used,&lt;/li&gt;
    &lt;li&gt;Creating an ambient &lt;i&gt;DataContext&lt;/i&gt; that is re-used automatically (avoids the
        extra argument required above),&lt;/li&gt;
    &lt;li&gt;Defining a custom Detach method for each of your entity classes that erases any
        connection to the original &lt;i&gt;DataContext&lt;/i&gt; instance,&lt;/li&gt;
    &lt;li&gt;Defining a generic Detach method that uses reflection to produce a copy of your
        entity without any connection to the original &lt;i&gt;DataContext&lt;/i&gt;,&lt;/li&gt;
    &lt;li&gt;Defining a generic Detach method that uses serialization to produce a copy of your
        entity.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
    None of these really seem like adequate solutions to me. They all introduce overhead
    (reflection or serialization) and/or complexity (extra arguments or maintaining
    a custom methods). The ambient &lt;i&gt;DataContext &lt;/i&gt;solution seemed intriguing at
    first, but also presents its own &lt;a href="http://dotnetlog.com/archive/2008/03/18/best-practice-and-effective-way-of-using-datacontext-in-linq.aspx"&gt;
        problems&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
    So after playing around with the framework some more, I've settled on my own solution:
    define a generic Detach method that copies the entity in the same way that entities
    are materialized. Namely, I'm going to use the &lt;i&gt;MetaModel&lt;/i&gt; provided by the
    &lt;i&gt;DataContext&lt;/i&gt; class. Here is Detach, provided by an ExtendedDataContext:
&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
public class ExtendedDataContext : DataContext
{
    /// &amp;lt;summary&amp;gt;
    /// Detaches an entity from its existing data context.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;typeparam name="TEntity"&amp;gt;The entity type.&amp;lt;/typeparam&amp;gt;
    /// &amp;lt;param name="entity"&amp;gt;The entity instance.
    /// &amp;lt;returns&amp;gt;A copy of the entity in a detached state.&amp;lt;/returns&amp;gt;
    public TEntity Detach&amp;lt;TEntity&amp;gt;(
      TEntity entity) where TEntity : class, new()
    {
        if (entity == null)
            return null;

        //create a copy of the entity
        object Copy = new TEntity();

        //enumerate the data member mappings for the entity type
        foreach (MetaDataMember member in Mapping.GetMetaType(typeof(TEntity)).DataMembers)
        {
            if (member.IsAssociation    //skip associations and deferred members
              || member.IsDeferred)
              continue;

            //copy the member value
            member.StorageAccessor.SetBoxedValue(
              ref Copy,
              member.StorageAccessor.GetBoxedValue(entity));
        }

        return (TEntity)Copy;
    }
}
&lt;/pre&gt;
&lt;p&gt;
    The algorithm is pretty concise: create a new instance of your entity and use its
    model metadata to copy data from the existing entity to the new instance. While
    copying, we skip associations and deferred members to avoid copying references to
    the original &lt;i&gt;DataContext &lt;/i&gt;instance.
&lt;/p&gt;
&lt;p&gt;
    Please notice that &lt;span style="font-weight: bold;"&gt;the constructor for your entity
        will be called each time the Detach method is called. This means that the OnCreated
        extension method will also be called.&lt;/span&gt; This may or may not be a problem
    for you, depending on what code, if any, you define for the OnCreated extension.
    I provide another method to help transfer ownership of an entity from one &lt;i&gt;DataContext&lt;/i&gt;
    to another, the Assume method:
&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
/// &amp;lt;summary&amp;gt;
/// Detaches an entity from its existing data context and re-attaches it to this data context.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name="TEntity"&amp;gt;The entity type.&amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name="entity"&amp;gt;The entity instance, which will be replaced by the detached instance.
/// &amp;lt;remarks&amp;gt;The entity instance is copied by this method.&amp;lt;/remarks&amp;gt;
public void Assume&amp;lt;TEntity&amp;gt;(
  ref TEntity entity) where TEntity : class, new()
{
    if (entity == null)
        return;

    entity = Detach(entity);
    GetTable&amp;lt;TEntity&amp;gt;().Attach(entity);
}
&lt;/pre&gt;
&lt;p&gt;
    Going back to our original application, we can use the designer to change the base
    class of the generated &lt;i&gt;CommunityDataContext&lt;/i&gt; to &lt;i&gt;ExtendedDataContext&lt;/i&gt;,
    and change our driver code to the following:
&lt;/p&gt;
&lt;pre class="prettyprint"&gt;Account User = Account.Login("someone@somewhere.com", "password");
if (User == null)
    throw new Exception("Login Failed.");

using (CommunityDataContext dc = new CommunityDataContext())
{
    dc.Assume(ref User);

    Post NewPost = new Post()
    {
        Account = User,
        Content = "Test Content"
    };

    dc.Posts.InsertOnSubmit(NewPost);
    dc.SubmitChanges();
}
&lt;/pre&gt;
&lt;p&gt;
    The above will now work as expected!  We can log in and get an &lt;i&gt;Account&lt;/i&gt; instance that was created by one &lt;i&gt;DataContext&lt;/i&gt;, and use that &lt;i&gt;Account&lt;/i&gt; when creating a new &lt;i&gt;Post&lt;/i&gt; in a later context.
&lt;/p&gt;
&lt;p&gt;
I think that there are some real strengths to this approach.
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You don't need to maintain any additional code to support each of your entities,&lt;/li&gt;
&lt;li&gt;You can utilize the existing information provided by the &lt;i&gt;MetaModel&lt;/i&gt; to avoid examining the entity type using reflection,&lt;/li&gt;
&lt;li&gt;This method works for entities mapped using either the &lt;i&gt;AttributeMappingSource&lt;/i&gt; or the &lt;i&gt;XmlMappingSource&lt;/i&gt;.
&lt;/ul&gt;
&lt;p&gt;
If you dig through the code used by the LINQ to SQL framework, you'll see the &lt;i&gt;MetaModel&lt;/i&gt; and related classes are used everywhere.  In particular, the framework uses the model to compile classes at runtime that extend &lt;i&gt;System.Data.Linq.SqlClientImplementation.ObjectMaterializer&amp;lt;&amp;gt;&lt;/i&gt; to provide faster materialization of entities (without reflection).  Perhaps a future extension of this method will do the same.
&lt;/p&gt;
&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6478488875010480037-885274682935427859?l=crefs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://crefs.blogspot.com/feeds/885274682935427859/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6478488875010480037&amp;postID=885274682935427859' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/885274682935427859'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/885274682935427859'/><link rel='alternate' type='text/html' href='http://crefs.blogspot.com/2008/08/detaching-linq-to-sql-entities.html' title='Detaching LINQ to SQL Entities'/><author><name>Michael Petito</name><uri>http://www.blogger.com/profile/13633541694266265970</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/_Ahq7bY519Zc/ScGSSQAmF8I/AAAAAAAAABo/r-uDjNj29rI/S220/photo.png'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6478488875010480037.post-6419948303530511485</id><published>2008-08-24T15:08:00.004-04:00</published><updated>2008-08-24T17:54:04.531-04:00</updated><title type='text'>Welcome</title><content type='html'>&lt;p&gt;There is an amazing array of knowledge available on other blogs relating to programming and specific software technologies.  Whenever I hit a roadblock on a project, or can't seem to come up with that &lt;span style="font-style: italic;"&gt;elegant &lt;/span&gt;solution to a problem, I frequently find someone who has blogged about the issue and come up with a useful alternative or solution.
&lt;/p&gt;
&lt;p&gt;It seems like there is a great community for building and sharing this kind of knowledge.  So, I'd like to start contributing my own ideas to see if I can't help others.
&lt;/p&gt;
&lt;p&gt;I'm not going to bind this blog to any particular software technology or platform; however, as I post more content you might quickly realize that the majority of my experience is with .NET and other Microsoft technologies.  This doesn't mean I'm not interested in leveraging other technologies, so feel free to comment on them as well.
&lt;/p&gt;
&lt;p&gt;I hope that you find the information here interesting and useful!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6478488875010480037-6419948303530511485?l=crefs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://crefs.blogspot.com/feeds/6419948303530511485/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=6478488875010480037&amp;postID=6419948303530511485' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/6419948303530511485'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6478488875010480037/posts/default/6419948303530511485'/><link rel='alternate' type='text/html' href='http://crefs.blogspot.com/2008/08/welcome.html' title='Welcome'/><author><name>Michael Petito</name><uri>http://www.blogger.com/profile/13633541694266265970</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/_Ahq7bY519Zc/ScGSSQAmF8I/AAAAAAAAABo/r-uDjNj29rI/S220/photo.png'/></author><thr:total>0</thr:total></entry></feed>
