04.07.2013 Views

Programming Entity Framework - Cdn.oreilly.com

Programming Entity Framework - Cdn.oreilly.com

Programming Entity Framework - Cdn.oreilly.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The first method builds a setter for the given property that includes code to perform<br />

validation on the length of the field. It calls the second method which takes an attribute<br />

name, such as MaxLength, and reads the metadata to return the value of that attribute,<br />

for example, 50, so that the setter can build the proper validation code as well as a<br />

helpful error message.<br />

Some of the code uses .NET Reflection, but some of it uses features of <strong>Entity</strong><br />

<strong>Framework</strong>’s MetadataWorkspace which knows how to read the metadata files.<br />

You will learn much more about the MetadataWorkspace in<br />

Chapter 21.<br />

For example, the code to return the attrib value uses the MetadataWorkspace<br />

TypeUsage method to find the MaxLength attribute. If the MaxLength attribute is<br />

found, the code first checks for three possible problems. If the MaxLength is empty, is<br />

set to SQL Server’s “Max” (e.g., varchar(Max)), or is a binary (Byte) field, the<br />

validation code is not written. Otherwise, the method builds up a string that will test the<br />

value of the property being set against the maximum length value. If the validation fails,<br />

an ArgumentException is thrown with a specific description of the problem. If<br />

MaxLength is not found, an empty string is returned.<br />

Example 13-12 shows the template function that will generate the validation code for<br />

you.<br />

Example 13-12. The T4 template code for generatingMaxLength validation<br />

string MaxLengthValidation(EdmProperty prop)<br />

{<br />

var attrib=prop.TypeUsage.Facets.FirstOrDefault(p=>p.Name=="MaxLength");<br />

if (attrib != null)<br />

{<br />

string aVal=GetAttributeValue(attrib);<br />

if (aVal == "Max" | aVal=="" | prop.TypeUsage.EdmType.Name == "Binary")<br />

return "";<br />

else<br />

{<br />

return System.Environment.NewLine +<br />

"if (value.Length > " + aVal + ") " + System.Environment.NewLine +<br />

new ArgumentException(\"" + prop.Name +<br />

" must be less than " + aVal +" characters\");" +<br />

System.Environment.NewLine +<br />

" else";<br />

}<br />

}<br />

else<br />

{<br />

return "";<br />

}<br />

}<br />

string GetAttributeValue(Facet attrib)<br />

{<br />

var aVal=attrib.Value;<br />

return Convert.ToString(aVal);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!