<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>E.V.I.C.T. B.V. &#187; Validation</title>
	<atom:link href="http://evict.nl/index.php/tag/validation/feed/" rel="self" type="application/rss+xml" />
	<link>http://evict.nl</link>
	<description>Playground of Edwin Vermeer</description>
	<lastBuildDate>Thu, 13 Oct 2011 11:44:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Get the field type from EntityFramework or linq2sql generated classes</title>
		<link>http://evict.nl/index.php/code/get-the-field-type-from-entityframework-or-linq2sql-generated-classes</link>
		<comments>http://evict.nl/index.php/code/get-the-field-type-from-entityframework-or-linq2sql-generated-classes#comments</comments>
		<pubDate>Thu, 04 Mar 2010 23:13:30 +0000</pubDate>
		<dc:creator>Edwin Vermeer</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DbType]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Linq2sql]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://evict.nl/?p=285</guid>
		<description><![CDATA[After generating classes and properties using the Entity Framework or Linq2sql you somtimes want to know in your code how big a database field is. Probably that would be for doing some input validation. The best way to do that is of course asking that information from the database. But wait&#8230; Didn&#8217;t we made a [...]]]></description>
			<content:encoded><![CDATA[<p><!--:en-->After generating classes and properties using the Entity Framework or Linq2sql you somtimes want to know in your code how big a database field is. Probably that would be for doing some input validation. The best way to do that is of course asking that information from the database.</p>
<p>But wait&#8230; Didn&#8217;t we made a .dbml which generated a couple of classes for the tables in our database? The information we need should be in one of the files that is generated by the .dbml. When you search through the .cs file for your classes and fields, you will see that the properties that are linked to your databse contain a ColumnAttribute. See this code snippet:</p>
<pre class="brush: c#">
[Column(Storage=&quot;_id&quot;, AutoSync=AutoSync.OnInsert, DbType=&quot;Int NOT NULL IDENTITY&quot;, IsPrimaryKey=true, IsDbGenerated=true)]
public int id
{ …

[Column(Name=&quot;name&quot;, Storage=&quot;_name&quot;, DbType=&quot;VarChar(150) NOT NULL&quot;, CanBeNull=false)]
public string name
{ …
</pre>
<p>Here you see that de database field type is specified in the DbType attribute field. So that is wat we want to know in our code. We just have to find an easy way for getting this information. For this I created a Reflection Utility class. Here is the code:</p>
<pre class="brush: c#">
public static class ReflectionUtility
{
    public static string GetPropertyName&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt;  expression)
    {
        return ((MemberExpression)expression.Body).Member.Name;
    }
    public static ColumnAttribute GetColumnAttribute&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expression)
    {
        string propertyName = ((MemberExpression)expression.Body).Member.Name;
        Type type = ((MemberExpression)expression.Body).Member.ReflectedType;
        PropertyInfo memberInfo = type.GetProperty(propertyName, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        object[] attributes = memberInfo.GetCustomAttributes(typeof(ColumnAttribute), false);
        foreach (var attribute in attributes)
        {
            var columnAttribute = attribute as ColumnAttribute;
            if (columnAttribute != null) return columnAttribute;
        }
        return null;
    }
    public static string GetDbType&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expression)
    {
        ColumnAttribute attribute = GetColumnAttribute(expression);
        return (attribute != null) ? attribute.DbType : null;
    }
}
</pre>
<p>As you can see getting the information can easilly be done with some simple reflection. I even made sure you could query both public and non public properties (internal). After you added the ReflectionUtility class to your solution you can get the DbType of a property or just the name of a property with one simple line of code. Her is a sample of how you can use it:</p>
<pre class="brush: c#">
string fieldName = ReflectionUtility.GetPropertyName(() =&gt; (new user()).id);
string dbType = ReflectionUtility.GetDbType(() =&gt; (new user()).name);
</pre>
<p>As you can see you only need one simple line of code for getting the database type information from a property. I am not even using &#8216;magic strings&#8217; for doing the reflection. I just pass the property itself to the method. The bennefit of this is that after a refactoring (changing the name of a property) you don&#8217;t even have to try to find all the property name string and replace them by the new name.</p>
<p>There is one drawback for getting the field type information this way. It is possible to enter something in your .dbml that is different from the actual field type in the database. For instance you could set the size smaller than the actual field size.</p>
<h2>Conclusion:</h2>
<p>This was a fun exersize. If you think that the DbType information in your .dbml is good, then using this utility class is a very easy way to get the type information. There are a couple of things that could be done for improving this code. For instance you could parse the field type string into an object or you could make a validator method that wil check if the current value is not longer that the field length.<!--:--></p>
<h2  class="related_post_title">Related posts</h2><ul class="related_post"><li>July 4, 2010 -- <a href="http://evict.nl/index.php/code/extension-methods-not-always-a-good-thing" title="Extension methods: Not always a good thing.">Extension methods: Not always a good thing.</a> (0)</li><li>January 26, 2010 -- <a href="http://evict.nl/index.php/code/converting-a-generic-list-to-one-of-its-interfaces-or-base-types" title="Converting a generic list to one of its interfaces or base class">Converting a generic list to one of its interfaces or base class</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://evict.nl/index.php/code/get-the-field-type-from-entityframework-or-linq2sql-generated-classes/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

