<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Sayed Ibrahim Hashimi - MSBuild, Web Deploy (MSDeploy), ASP.NET - Entity</title>
    <link>http://sedodream.com/</link>
    <description>MSBuild, C#, Visual Studio and more</description>
    <language>en-us</language>
    <copyright>Sayed Ibrahim Hashimi</copyright>
    <lastBuildDate>Fri, 09 Apr 2010 01:49:32 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>sayed.hashimi@gmail.com</managingEditor>
    <webMaster>sayed.hashimi@gmail.com</webMaster>
    <item>
      <trackback:ping>http://sedodream.com/Trackback.aspx?guid=a33d943a-3ad7-48a9-aa25-3e3d6b20572e</trackback:ping>
      <pingback:server>http://sedodream.com/pingback.aspx</pingback:server>
      <pingback:target>http://sedodream.com/PermaLink,guid,a33d943a-3ad7-48a9-aa25-3e3d6b20572e.aspx</pingback:target>
      <dc:creator>Ibrahim</dc:creator>
      <wfw:comment>http://sedodream.com/CommentView,guid,a33d943a-3ad7-48a9-aa25-3e3d6b20572e.aspx</wfw:comment>
      <wfw:commentRss>http://sedodream.com/SyndicationService.asmx/GetEntryCommentsRss?guid=a33d943a-3ad7-48a9-aa25-3e3d6b20572e</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Today a friend of mine asked me to explain (<em>via email</em>) a few things to another
developer regarding some things I have done with the Entity Framework (EF). I figured
since I already typed it up I might as well share it here as well. So here it is.
</p>
        <p>
I have had 2 issues with using EF4 which I have found creative and effective work
around for.
</p>
        <p>
          <b>
            <u>Externalizing filters</u>
          </b>
        </p>
        <p>
The first issue, which also exists when using other frameworks, is that you end up
with an explosion of methods (<i>and usually a lot of duplicated code</i>). For instance
let’s say you have a table to store users. This table has an ID, and Email field and,
and let’s and OpenIdUrl. So you end up with the following methods.
</p>
        <pre class="brush: csharp;">User GetUserById(long id)

User GetUserByEmail(string email)

User GetUserByOpenIdUrl(string openIdUrl)</pre>
        <p>
Usually you’ll find that each of these methods have the exact same implementation
except a different where clause. Now there is a bigger problem in the fact that you
cannot anticipate everything that the user may want to filter on. Because of this
and the dynamic nature of IQueryable I have employed a technique using Expression
Trees to allow the user to declare the exact filter to be used via a lambda expression.
So for the users it’s very slick. For example I could create the following method
</p>
        <pre class="brush: csharp;">public User GetUser(Expression&lt;Func&lt;User, bool&gt;&gt; filter)
{
    if (filter == null)
    {
        filter = Const&lt;User&gt;.LinqExpression.LinqExpressionFuncAlwaysTrue;
    }

    User foundUser = null;
    using (InlineTasksContext dbContext = new InlineTasksContext())
    {
        dbContext.Connection.Open();
        foundUser = dbContext.Users.Where(filter).SingleIfExists();
    }

    return foundUser;
}</pre>
        <p>
In this case I’m allowing the user to pass in a filter that is applied to the query.
Here is how I could implement those three if I chose to as well.
</p>
        <pre class="brush: csharp;">public User GetUserById(long id)
{
    return this.GetUser(user =&gt; user.Id == id);
}
public User GetUserByEmail(string email)
{
    if (email == null) { throw new System.ArgumentNullException("email"); }

    return GetUser(user =&gt; user.Email == email);
}
public User GetUserByOpenIdUrl(string openIdUrl)
{
    if (string.IsNullOrEmpty(openIdUrl)) { throw new ArgumentNullException("openIdUrl"); }

    return GetUser(user =&gt; user.OpenIdUrl == openIdUrl);
}</pre>
        <p>
Note in the first method I am using some other helpers I created. Specifically the <strong><em>Const&lt;User&gt;.LinqExpression.LinqExpressionFuncAlwaysTrue</em></strong> as
well as the <strong><em>SingleIfExists</em></strong></p>
        <p>
extension method. I use the <strong><em>AlwaysTrue</em></strong> expression so that
way I don’t have to be worried about doing an if and having to maintain 2 select statements.
And the other (<strong><em>SingleIfExists</em></strong>) is used to just return null
instead of blowing up if no elements exist in the sequence.
</p>
        <p>
Since they are not the purpose of this email I’ve just put them at the bottom so that
you can read if you are interested.
</p>
        <p>
As Keith mentioned to me a while back Expression trees are not serializable so you
still end up with this problem if you are using a service based solution. But you
could try and use the sample <a href="http://code.msdn.microsoft.com/exprserialization">Expression
Tree Serialization</a> to take care of this for you, I’ve never tried it, but it’s
on my TODO list.
</p>
        <p>
          <b>
            <u>.Include</u>
          </b>
        </p>
        <p>
My next issue is that you are forced to declare what navigation properties (i.e. table
links) should be included in the query. This is done using the .Include method. So
back to our GetUser example, how can a framework know what tables values should be
extracted for? The end result is that the framework creator just includes a bunch
of tables and 90% of the time the result is just wasted resources because the other
data is never touched. Better is to provide a default which only includes the most
commonly used tables and another method that allows them to specify what they want.
Here is a sample for a <strong><em>GetTasksByUserId</em></strong> method
</p>
        <pre class="brush: csharp;">public IList&lt;Task&gt; GetTasksByUserId(long userId, IEnumerable&lt;string&gt; includeList)
{
    using (InlineTasksContext dbContext = new InlineTasksContext())
    {
        var result = (from t in dbContext.Tasks
                        .Include(includeList)
                        .Where(t=&gt;t.User.Id == 1)
                        select t)
                        .ToList();
        return result;
    }
}
 In this example I’m using an extension method for.Include which is defined as follows.
public static ObjectQuery&lt;T&gt; Include&lt;T&gt;(this ObjectQuery&lt;T&gt; query, IEnumerable&lt;string&gt; includes)
{
    if (query == null) { throw new System.ArgumentNullException("query"); }

    if (includes != null)
    {
        foreach (string include in includes)
        {
            query.Include(include);
        }
    }
    return query;
}</pre>
        <p>
So the idea is to create a framework which is both robust and easy to use, but at
the same time is not overly assumptive about what the users want. I think a lot more
can be done with EF and its dynamic nature.
</p>
        <p>
Does that cover what you were intending Keith? Any questions/comments please send
them my way.
</p>
        <p>
          <b>
            <u>Here are those methods I mentioned above.</u>
          </b>
        </p>
        <pre class="brush: csharp;">public static class LinqExtensions
{
    public static T SingleIfExists&lt;T&gt;(this IQueryable&lt;T&gt; query)
    {
        if (query == null) { throw new System.ArgumentNullException("query"); }

        T result = default(T);
        if (query.Count() &gt; 0)
        {
            result = query.Single();
        }

        return result;
    }
}
//----------------------------------------------------------------------------------------------------
public class Const&lt;T&gt;
{
    public static class Predicate
    {
        public static Predicate&lt;T&gt; AlwaysTrue
        {
            get
            {
                return x =&gt; true;
            }
        }

        public static Predicate&lt;T&gt; AlwaysFalse
        {
            get
            {
                return x =&gt; false;
            }
        }
    }

    public class LinqExpression
    {
        public static Expression&lt;Func&lt;T, bool&gt;&gt; LinqExpressionFuncAlwaysTrue
        {
            get
            {
                return x =&gt; true;
            }
        }
    }
}</pre>
Sayed Ibrahim Hashimi</body>
      <title>Entity Framework: Externalizing filters and dynamic includes</title>
      <guid isPermaLink="false">http://sedodream.com/PermaLink,guid,a33d943a-3ad7-48a9-aa25-3e3d6b20572e.aspx</guid>
      <link>http://sedodream.com/2010/04/09/EntityFrameworkExternalizingFiltersAndDynamicIncludes.aspx</link>
      <pubDate>Fri, 09 Apr 2010 01:49:32 GMT</pubDate>
      <description>&lt;p&gt;
Today a friend of mine asked me to explain (&lt;em&gt;via email&lt;/em&gt;) a few things to another
developer regarding some things I have done with the Entity Framework (EF). I figured
since I already typed it up I might as well share it here as well. So here it is.
&lt;/p&gt;
&lt;p&gt;
I have had 2 issues with using EF4 which I have found creative and effective work
around for.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;&lt;u&gt;Externalizing filters&lt;/u&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The first issue, which also exists when using other frameworks, is that you end up
with an explosion of methods (&lt;i&gt;and usually a lot of duplicated code&lt;/i&gt;). For instance
let’s say you have a table to store users. This table has an ID, and Email field and,
and let’s and OpenIdUrl. So you end up with the following methods.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;User GetUserById(long id)

User GetUserByEmail(string email)

User GetUserByOpenIdUrl(string openIdUrl)&lt;/pre&gt;
&lt;p&gt;
Usually you’ll find that each of these methods have the exact same implementation
except a different where clause. Now there is a bigger problem in the fact that you
cannot anticipate everything that the user may want to filter on. Because of this
and the dynamic nature of IQueryable I have employed a technique using Expression
Trees to allow the user to declare the exact filter to be used via a lambda expression.
So for the users it’s very slick. For example I could create the following method
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public User GetUser(Expression&amp;lt;Func&amp;lt;User, bool&amp;gt;&amp;gt; filter)
{
    if (filter == null)
    {
        filter = Const&amp;lt;User&amp;gt;.LinqExpression.LinqExpressionFuncAlwaysTrue;
    }

    User foundUser = null;
    using (InlineTasksContext dbContext = new InlineTasksContext())
    {
        dbContext.Connection.Open();
        foundUser = dbContext.Users.Where(filter).SingleIfExists();
    }

    return foundUser;
}&lt;/pre&gt;
&lt;p&gt;
In this case I’m allowing the user to pass in a filter that is applied to the query.
Here is how I could implement those three if I chose to as well.
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public User GetUserById(long id)
{
    return this.GetUser(user =&amp;gt; user.Id == id);
}
public User GetUserByEmail(string email)
{
    if (email == null) { throw new System.ArgumentNullException("email"); }

    return GetUser(user =&amp;gt; user.Email == email);
}
public User GetUserByOpenIdUrl(string openIdUrl)
{
    if (string.IsNullOrEmpty(openIdUrl)) { throw new ArgumentNullException("openIdUrl"); }

    return GetUser(user =&amp;gt; user.OpenIdUrl == openIdUrl);
}&lt;/pre&gt;
&lt;p&gt;
Note in the first method I am using some other helpers I created. Specifically the &lt;strong&gt;&lt;em&gt;Const&amp;lt;User&amp;gt;.LinqExpression.LinqExpressionFuncAlwaysTrue&lt;/em&gt;&lt;/strong&gt; as
well as the &lt;strong&gt;&lt;em&gt;SingleIfExists&lt;/em&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
extension method. I use the &lt;strong&gt;&lt;em&gt;AlwaysTrue&lt;/em&gt;&lt;/strong&gt; expression so that
way I don’t have to be worried about doing an if and having to maintain 2 select statements.
And the other (&lt;strong&gt;&lt;em&gt;SingleIfExists&lt;/em&gt;&lt;/strong&gt;) is used to just return null
instead of blowing up if no elements exist in the sequence.
&lt;/p&gt;
&lt;p&gt;
Since they are not the purpose of this email I’ve just put them at the bottom so that
you can read if you are interested.
&lt;/p&gt;
&lt;p&gt;
As Keith mentioned to me a while back Expression trees are not serializable so you
still end up with this problem if you are using a service based solution. But you
could try and use the sample &lt;a href="http://code.msdn.microsoft.com/exprserialization"&gt;Expression
Tree Serialization&lt;/a&gt; to take care of this for you, I’ve never tried it, but it’s
on my TODO list.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;&lt;u&gt;.Include&lt;/u&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
My next issue is that you are forced to declare what navigation properties (i.e. table
links) should be included in the query. This is done using the .Include method. So
back to our GetUser example, how can a framework know what tables values should be
extracted for? The end result is that the framework creator just includes a bunch
of tables and 90% of the time the result is just wasted resources because the other
data is never touched. Better is to provide a default which only includes the most
commonly used tables and another method that allows them to specify what they want.
Here is a sample for a &lt;strong&gt;&lt;em&gt;GetTasksByUserId&lt;/em&gt;&lt;/strong&gt; method
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public IList&amp;lt;Task&amp;gt; GetTasksByUserId(long userId, IEnumerable&amp;lt;string&amp;gt; includeList)
{
    using (InlineTasksContext dbContext = new InlineTasksContext())
    {
        var result = (from t in dbContext.Tasks
                        .Include(includeList)
                        .Where(t=&amp;gt;t.User.Id == 1)
                        select t)
                        .ToList();
        return result;
    }
}
 In this example I’m using an extension method for.Include which is defined as follows.
public static ObjectQuery&amp;lt;T&amp;gt; Include&amp;lt;T&amp;gt;(this ObjectQuery&amp;lt;T&amp;gt; query, IEnumerable&amp;lt;string&amp;gt; includes)
{
    if (query == null) { throw new System.ArgumentNullException("query"); }

    if (includes != null)
    {
        foreach (string include in includes)
        {
            query.Include(include);
        }
    }
    return query;
}&lt;/pre&gt;
&lt;p&gt;
So the idea is to create a framework which is both robust and easy to use, but at
the same time is not overly assumptive about what the users want. I think a lot more
can be done with EF and its dynamic nature.
&lt;/p&gt;
&lt;p&gt;
Does that cover what you were intending Keith? Any questions/comments please send
them my way.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;&lt;u&gt;Here are those methods I mentioned above.&lt;/u&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public static class LinqExtensions
{
    public static T SingleIfExists&amp;lt;T&amp;gt;(this IQueryable&amp;lt;T&amp;gt; query)
    {
        if (query == null) { throw new System.ArgumentNullException("query"); }

        T result = default(T);
        if (query.Count() &amp;gt; 0)
        {
            result = query.Single();
        }

        return result;
    }
}
//----------------------------------------------------------------------------------------------------
public class Const&amp;lt;T&amp;gt;
{
    public static class Predicate
    {
        public static Predicate&amp;lt;T&amp;gt; AlwaysTrue
        {
            get
            {
                return x =&amp;gt; true;
            }
        }

        public static Predicate&amp;lt;T&amp;gt; AlwaysFalse
        {
            get
            {
                return x =&amp;gt; false;
            }
        }
    }

    public class LinqExpression
    {
        public static Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; LinqExpressionFuncAlwaysTrue
        {
            get
            {
                return x =&amp;gt; true;
            }
        }
    }
}&lt;/pre&gt;

Sayed Ibrahim Hashimi</description>
      <comments>http://sedodream.com/CommentView,guid,a33d943a-3ad7-48a9-aa25-3e3d6b20572e.aspx</comments>
      <category>Entity</category>
      <category>Entity Framework</category>
      <category>LINQ</category>
    </item>
  </channel>
</rss>