﻿<?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>Programming By A Tool &#187; Entity Framework</title>
	<atom:link href="http://byatool.com/tag/entity-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>ARE YOU NOT ENTERTAINED?</description>
	<lastBuildDate>Wed, 28 Jul 2010 18:01:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</title>
		<link>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/</link>
		<comments>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/#comments</comments>
		<pubDate>Wed, 28 Oct 2009 15:41:52 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1043</guid>
		<description><![CDATA[So something I've seen but just have now conquered is the whole complex type thing in Entity Framework. Not only that, but with the cool new Persistence Ignorance thing all the kids are talking about. (And boy am I glad there's a new kind of ignorance on this site now.) You might ask: What's a [...]]]></description>
			<content:encoded><![CDATA[<p>So something I've seen but just have now conquered is the whole complex type thing in Entity Framework.  Not only that, but with the cool new Persistence Ignorance thing all the kids are talking about.  (And boy am I glad there's a new kind of ignorance on this site now.)  You might ask:  What's a complex type?  Course you might ask:  Why is it so hard to make a decent movie about huge robots that transform into cool vehicles and have really big guns?  Well I can answer the first question.</p>
<p>Complex types, in the simple minded way I see them, are a way to split information retrieved from a table into a object within an object.  Confused yet?  I hope so.</p>
<p>Say you have a User table and on that table you have the typical user information including a bunch of stuff like Name, Sex, City, State, and Zip.  Now you could set up the user class to look like this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">User</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> City { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> State { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Zip { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Nothing wrong with that, but what if you have an Address class:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Address</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> City { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> State { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Zip { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>That you wanted to map the values from the User table to the User class to so that the User class looked more like this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">User</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Address</span> Address { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Well I'm here to tell you that you can and I have plenty of pictures to back it up.</p>
<p>Keeping with the design <a href="http://byatool.com/index.php/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/">from this guy</a>, I am going to add a new class called AdDimension which will have Height and Width, effectively replacing the Height and Width properties on the Ad class.</p>
<p>RECAP - Old class diagram:</p>
<pre><img class="alignnone size-full wp-image-1054" title="AddAdtype" src="http://byatool.com/wp-content/uploads/2009/10/AddAdtype.png" alt="AddAdtype" width="421" height="528" /></pre>
<p>So the first thing I have to do is is create the complex type in the Model Browser.  That's pretty easy.  There's a section called "Complex Types" and you just add one.</p>
<pre><img class="alignnone size-full wp-image-1055" title="ComplexTypeAdd" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypeAdd.png" alt="ComplexTypeAdd" width="527" height="364" /></pre>
<p>See, there's a picture.  Next step is adding properties to the newly created complex type.</p>
<pre><img class="alignnone size-full wp-image-1062" title="ComplexTypePropertyAdd" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypePropertyAdd3.png" alt="ComplexTypePropertyAdd" width="537" height="494" /></pre>
<p>Another picture!  Ok so now you've created on, big deal.  Now what?  Well you have to add a complex type property to the main class, Ad in this case.</p>
<pre><img class="alignnone size-full wp-image-1065" title="ComplexTypeAddToEntity" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypeAddToEntity1.png" alt="ComplexTypeAddToEntity" width="643" height="525" /></pre>
<p>Now if you have more than one complex type, you might have to set the property type to the correct one.  Just right click the complex property and click on properties:</p>
<pre><img class="alignnone size-full wp-image-1063" title="ComplexTypePropertyProperties" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypePropertyProperties.png" alt="ComplexTypePropertyProperties" width="307" height="268" /></pre>
<p>Now, you'll have to adjust the mapping for the entity itself.  So click on the object and bring up mapping properties.  From there, select the correct mapping for the correct column.  In this example it's width and as you can see in the drop down there is a AdDimension.Width property to set it to.  Cool huh?</p>
<pre><img class="alignnone size-full wp-image-1059" title="ComplexTypeSetMapping" src="http://byatool.com/wp-content/uploads/2009/10/ComplexTypeSetMapping.png" alt="ComplexTypeSetMapping" width="800" height="195" /></pre>
<p>And that's it for the object model.  Next you have to add the AdDimension class and add a property to the Ad class.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AdDimension</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Height { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Width { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Ad</span>
  {
    ...
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">AdDimension</span> <span style="color: #000000;">AdDimension</span> { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<p>And then how do you set it?</p>
<pre>  someAd.AdDimension = <span style="color: #0000ff;">new</span> <span style="color: #008080;">AdDimension</span>();
  someAd.AdDimension.Height = 10;
  someAd.AdDimension.Width = 10;</pre>
<p>And it can even be used in queries:</p>
<pre>  context.Ads.Where(ad =&gt; ad.Width &gt; 10);</pre>
<p>Now there are things to be aware of.  Complex types can't inherit from other complex types and the property can't be null when saving.  Just be aware of that.</p>
<p>I'm telling you man, this s-- is the s--- man.  It's the s---.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li><li><a href="http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/" title="Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types">Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</title>
		<link>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/</link>
		<comments>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 17:34:08 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1036</guid>
		<description><![CDATA[So the next step in the New Entity Framework saga was to make a many to one relationship and get it to save. After all, with the last version I had far more issues with many to one than any other kind of relationship. Turns out, the steak is still in tact. Taking the structure [...]]]></description>
			<content:encoded><![CDATA[<p>So the next step in the New Entity Framework saga was to make a many to one relationship and get it to save. After all, with the last version I had far more issues with many to one than any other kind of relationship. Turns out, the steak is still in tact.</p>
<p><a href="http://byatool.com/index.php/lessons/net-4-0-beta-2-entity-framework-how-to-start/">Taking the structure from the last post</a>, I added an AdType. It's very simple. Columns are AdTypeId (Int Primary) and Description (Varchar). I added a AdTypeId column to the Ad table and created a foreign key to the AdType table with it.</p>
<p>Basically Many Ads to One AdType.</p>
<p>Then I did the usual Update Model From Database with the .edmx file. Same old same old. Well this added the AdType class and the relationship:</p>
<pre><img class="alignnone size-full wp-image-1054" title="AddAdtype" src="http://byatool.com/wp-content/uploads/2009/10/AddAdtype.png" alt="AddAdtype" width="421" height="528" /></pre>
<p>So far, so good. Now with this it also means that I need to create the AdType class and add the AdType property to the Ad class along with the AdTypeId property.</p>
<blockquote><p>Side Note:</p>
<p>Far as I can tell, you need the AdTypeId property despite also having the AdType property. Don't forget this.</p></blockquote>
<p>Here's the AdType class:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AdType
</span>  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Description { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Ad</span>&gt; Ads { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>And on the Ad class I had to "Ad" (HARHRHARHR) the AdType property along with the AdTypeId property:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Ad</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> CreatedDate { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span>? LastUpdated { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Height { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Width { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #008000;">//Interesting note: Works even if this is private and non virtual</span>
    <span style="color: #0000ff;">private</span> <span style="color: #008080;">Int32</span> AdTypeId { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">AdType</span> AdType { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #008000;">//Note:</span>
    <span style="color: #008000;">//If properties are to be lazy loaded, must be virtual</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newpaper</span>&gt; Newspapers { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Classes are done. Should be good to go right? WRONG YOU ARE SO F-ING WRONG! Just try this, I dare you:</p>
<pre>   <span style="color: #008080;">Ad</span> ad = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Ad</span>();

   ...
   ad.AdType = someAdType();
   context.Ads.Add(ad);
   context.SaveChanges();</pre>
<p><strong>DUN DUN DUUUUN INSERT statement conflicted with the FOREIGN KEY constraint.</strong></p>
<p>You try it? Idiot. You just got stuffed by a foreign key error. Why? <a href="http://blogs.msdn.com/adonet/archive/2009/06/10/poco-in-the-entity-framework-part-3-change-tracking-with-poco.aspx">Well The Big M has an answer:</a></p>
<blockquote><p>In this example, Customer is a pure POCO type. Unlike with EntityObject or IPOCO based entities, making changes to the entity doesn't automatically keep the state manager in sync because there is no automatic notification between your pure POCO entities and the Entity Framework. Therefore, upon querying the state manager, it thinks that the customer object state is Unchanged even though we have explicitly made a change to one of the properties on the entity.</p></blockquote>
<p>Basically because these objects aren't really being watched by the State Manager, it has no idea anything has changed and should be persisted. Therefore, it has no idea that the AdType property has changed and that the AdTypeId should be updated to reflect this. That's right, it just ignored the AdType property and left the AdTypeId to it's default... 0 (That's a Zero or as the English say, Zed).  How do you get around this? <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.saveoptions(VS.100).aspx">This little option.</a></p>
<pre>  context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);</pre>
<p>This tells it to persist the changes that it didn't know about.  Now I'm still picking this up as I go so bare with me as I might have the best explanations yet on why things work with the New Entity Framework.  Then again, this is a site by a tool.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li><li><a href="http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/" title="Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types">Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</title>
		<link>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/</link>
		<comments>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 20:41:19 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[4.0]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1017</guid>
		<description><![CDATA[So I just recently turned my laptop into a 4.0 workstation since it is kind of expendable and I won't feel inclined to nerd rage if it gets tooled. With this step forward, I decided that I probably won't be doing much with the old Entity Framework version since the new one is supposed to [...]]]></description>
			<content:encoded><![CDATA[<p>So I just recently turned my laptop into a 4.0 workstation since it is kind of expendable and I won't feel inclined to nerd rage if it gets tooled. With this step forward, I decided that I probably won't be doing much with the old Entity Framework version since the new one is supposed to be the end all/be all until the next end all/be all version comes out. What does this mean for you? This post could be filled with useful information or f--- all. Just depends on what you care about.</p>
<p>After doing a little reading, and by little I mean as little as humanly possible while still having an idea of what I'm doing, I got the new EF to persist an object. Mind you, it took a bit of patience followed by slamming my head into my desk and then more patience, but I did it.</p>
<p>First off, the actual creating of the edmx file is the same, there's really no difference. You still go through the wizard, you still go through the connection set up, and you still grab the tables you want. No change there.</p>
<p>However, once you have it created, click on the .edmx file in your solution explorer, right click, then click properties. You'll see something like this:</p>
<pre><img class="alignnone size-full wp-image-1021" title="BAT - EntityFramework_RemoveCustomTool" src="http://byatool.com/wp-content/uploads/2009/10/BAT-EntityFramework_RemoveCustomTool.png" alt="BAT - EntityFramework_RemoveCustomTool" width="380" height="355" /></pre>
<p>You can see where there is nothing in the Custom Tool area of properties. That's because I deleted the text. That's the first part of what you need to do. Next is creating the needed classes. For this example I have two, Ad and Newspaper:</p>
<pre><span style="color: #0000ff;">namespace</span> Beta2Test.Data.Entity
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Ad</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> CreatedDate { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span>? LastUpdated { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Height { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Width { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #008000;">//Note:</span>
    <span style="color: #008000;">//If properties are to be lazy loaded, must be virtual</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newspaper</span>&gt; Newspapers { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }
}</pre>
<p>and</p>
<pre><span style="color: #0000ff;">namespace</span> Beta2Test.Data.Entity
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Newspaper</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Id { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int32</span> Circulation { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> CreatedDate { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">DateTime</span> LastUpdated { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }

    <span style="color: #008000;">//Note:
</span>    <span style="color: #008000;">//If properties are to be lazy loaded, must be virtual</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">virtual</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Ad</span>&gt; Ads { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }
}</pre>
<p>Three things you might notice:</p>
<ol>
<li>The classes don't inherit from anything. Yay</li>
<li>The namespace is Beta2Test.Data.Entity. Fact is, I left it there to show that the namespace can now be anything. Yay</li>
<li>Both collection properties are virtual. This is a must when dealing with collections that represent a relationship and you have lazy loading enabled (See below context class). For this, there is a many to many relationship between Ads and Newpapers. The Ads and Newspapers collection represent that. Why do that have to be virtual? Has to do with Entity Framework needing a way to override the properties so it can tell when they are accessed. (Read: Lazy Loading)</li>
<li>There is no fourth thing. You are wrong if you think there is.</li>
</ol>
<p>So far so good, but what about that like whole linking to that persistence layer stuff. You know like them entity objects yo.</p>
<p>Thank you for that poorly worded inquiry, but valid none the less. Remember those entity context classes that it used to generate for you? Well that whole "custom tool" dohickey I removed would have built it for me. However, that's not the path we're going down anymore. It's now time to brave the unknown. We, yes we, will build the context. Yes the context.</p>
<pre><span style="color: #0000ff;">using</span> System.Data.Objects;
<span style="color: #0000ff;">using</span> Beta2Test.Data.Entity;

<span style="color: #0000ff;">namespace</span> Beta2Test.Data
{
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">Beta2TestContext</span> : <span style="color: #008080;">ObjectContext</span>
  {
    <span style="color: #0000ff;">private</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Ad</span>&gt; _ads;
    <span style="color: #0000ff;">private</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Newspaper</span>&gt; _newspapers;

    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Beta2TestContext</span>() : <span style="color: #0000ff;">base</span>(<span style="color: #800000;">"name=InterviewDemoEntities"</span>, <span style="color: #800000;">"InterviewDemoEntities"</span>)
    {
      _ads = <span style="color: #008080;">CreateObjectSet</span>&lt;<span style="color: #008080;">Ad</span>&gt;();
      _newspapers = <span style="color: #008080;">CreateObjectSet</span>&lt;<span style="color: #008080;">Newspaper</span>&gt;();

      <span style="color: #008000;">//This makes sure the context lazy loads by default</span>
      ContextOptions.LazyLoadingEnabled = <span style="color: #0000ff;">true</span>;
    }

    <span style="color: #008000;">///
</span>    <span style="color: #008000;">/// This is used to set up the "queryable" collection.</span>
    <span style="color: #008000;">///</span>
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Ad</span>&gt; Ads
    {
      <span style="color: #0000ff;">get</span>
      {
        <span style="color: #0000ff;">return</span> _ads;
      }
    }

    <span style="color: #0000ff;">public</span> <span style="color: #008080;">ObjectSet</span>&lt;<span style="color: #008080;">Newspaper</span>&gt; Newspapers
    {
      <span style="color: #0000ff;">get</span>
      {
        <span style="color: #0000ff;">return</span> _newspapers;
      }
    }

    <span style="color: #008000;">///</span>
    <span style="color: #008000;">/// This creates an ad that allows it "to be used with the Entity Framework."</span>
    <span style="color: #008000;">///</span>
    <span style="color: #008000;">///</span>
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Ad</span> CreateAttachedAd()
    {
      <span style="color: #0000ff;">return</span> <span style="color: #008080;">EntityContext</span>.Context.CreateObject&lt;<span style="color: #008080;">Ad</span>&gt;();
    }

    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Newspaper</span> CreateAttachedNewspaper()
    {
      <span style="color: #0000ff;">return</span> <span style="color: #008080;">EntityContext</span>.Context.CreateObject&lt;<span style="color: #008080;">Newspaper</span>&gt;();
    }
  }
}</pre>
<p>The CreateAttached methods aren't needed on the Context class itself, I just put them there. They could go on the Ad/Newspaper class but at this point I'm not sure if that blurs the lines or not. Haven't gotten into best practices mode yet.</p>
<p>You may notice the ObjectSet collections on the context. These are the collections you will query to get items most likely, much like the old context class from the last version:</p>
<pre>Context.Ads.Where(ad =&gt; ad.Id == 1)</pre>
<p>Pretty nice, huh?</p>
<p>Also, I noted above about the virtual properties on the Ad/Newspaper classes and how it had to do with lazy loading.</p>
<pre>ContextOptions.LazyLoadingEnabled = <span style="color: #0000ff;">true</span>;</pre>
<p>That line and the virtual properties ensure that lazy loading will occur when the property is used. Both have to be used together. Now you don't have to put that line in the constructor if you do create a context every time you are retrieving things, you could just set it on a case by case basis. Up to you. I use a <a href="http://byatool.com/index.php/pontification/singleton-objectcontext-the-remix/">singleton like context</a> so I just set it true in the constructor and don't worry about it.</p>
<p>The main thing I had trouble with was this line:</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #008080;">Beta2TestContext</span>() : <span style="color: #0000ff;">base</span>(<span style="color: #800000;">"name=InterviewDemoEntities"</span>, <span style="color: #800000;">"InterviewDemoEntities"</span>)</pre>
<p>Because I wasn't sure what the second string should be. First one is easy, it's whatever the key in the config file for the connection string. Second, chances are, is the same depending on how you set it all up in the wizard. I think it's the same name when you right click on the opened .edmx file and view properties. There should be a property named "Entity Container Name".</p>
<p>Here's a method I used for testing to create an Ad:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #008080;">Ad</span> CreateAd(<span style="color: #008080;">Boolean</span> persist)
  {
    <span style="color: #008080;">Ad</span> ad = <span style="color: #0000ff;">null</span>;

    <span style="color: #0000ff;">if</span> (persist)
    {
      ad = <span style="color: #008080;">EntityContext</span>.Context.CreateAttachedAd();  <span style="color: #008000;">//This is the CreateAttachedAd method above in use
</span>    }
    <span style="color: #0000ff;">else
</span>    {
      ad = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Ad</span>();
    }

    ad.CreatedDate = <span style="color: #008080;">DateTime</span>.UtcNow;
    ad.Height = <span style="color: #008080;">RandomTool</span>.RandomInt32(0, 10);
    ad.LastUpdated = <span style="color: #008080;">DateTime</span>.UtcNow;
    ad.Name = <span style="color: #008080;">RandomTool</span>.RandomString(10);
    ad.Width = <span style="color: #008080;">RandomTool</span>.RandomInt32(0, 10);

    <span style="color: #0000ff;">if</span> (persist)
    {
      AddEntityForRemoval(ad);  <span style="color: #008000;">//Ignore, for persistence removal after testing is completed</span>
      <span style="color: #008080;">EntityContext</span>.Context.Ads.AddObject(ad);  <span style="color: #008000;">//Ad the ... ad to the context</span>
      <span style="color: #008080;">EntityContext</span>.Context.SaveChanges();  <span style="color: #008000;">//Persist</span>
    }

    <span style="color: #0000ff;">return</span> ad;
  }</pre>
<p>There are some things you can ignore because I didn't feel like removing code. As you can see though, it's not very complicated. Use the CreateAttachedAd, fill in the properties, ad to the Ad collection on the context, and save.</p>
<p><strong>The End</strong></p>
<p>Sure you had to do more work than in the earlier version of Entity Framework, but on the other hand I have a fully detached class that can inherit from any class I WANT it to as opposed to the EntityObject class. Not to mention I now have an easy way to do lazy loading. Far cleaner than the <a href="http://byatool.com/index.php/pontification/entity-framework-possible-lazy-loading-solution/">old way I did it</a>. The other interesting thing to note, and this may not be a big deal to anyone else, but above I have a note about this:</p>
<pre>  AddEntityForRemoval(ad);  <span style="color: #008000;">//Ignore, for persistence removal after testing is completed</span></pre>
<p>This method just adds the object to a collection of EntityObjects that later I use to delete the object from the database on test cleanup. After moving to this version of EF, I had to change it to a collection of Objects. Interesting thing is:</p>
<pre>  <span style="color: #008080;">EntityContext</span>.Context.DeleteObject(currentObject);</pre>
<p>Didn't care. It still knew that the object was attached to the context somehow, despite the CLASS not being an EntityObject. Just an odd note.</p>
<p>Two Errors I came across:</p>
<blockquote><p>System.InvalidOperationException: Mapping and metadata information could not be found for EntityType 'Beta2Test.Data.Ad'.</p></blockquote>
<p>If you get this, there is a really good chance you screwed up a property name or are missing it completely. If the property name doesn't exactly match one in the .edmx class designer template, you're screwed. If you don't have it on the class but it's on the class designer template, you're screwed. If you add it to the class designer template, it has to be on the class as far as I can tell. Now, it doesn't have to be public. I have tested it as private and it works just fine.</p>
<blockquote><p>The required property 'Newspapers' does not exist on the type 'Beta2Test.Data.Ad'.</p></blockquote>
<p>This most likely happens if you didn't remember to make it a property:</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newpaper</span>&gt; Newpapers;  <span style="color: #008000;">//Forgot the { get; set; }</span></pre>
<pre><span style="color: #0000ff;">public</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">Newpaper</span>&gt; Newpapers { get; set; };  <span style="color: #008000;">//Forgot the Virtual</span></pre>
<p>Opps.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li><li><a href="http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/" title="Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types">Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Entity Framework:  Am I Just Being Stubborn?</title>
		<link>http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/</link>
		<comments>http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 16:08:40 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=756</guid>
		<description><![CDATA[Before I started using The EF, I had a couple years of use with LLBLGEN and about a year into NHibernate. I started dabbling with Linq to Sql for a bit but found it a bit lacking (As it was new, go figure) and decided to go forward with Entity Framework due to the fact [...]]]></description>
			<content:encoded><![CDATA[<p>Before I started using The EF, I had a couple years of use with LLBLGEN and about a year into NHibernate. I started dabbling with Linq to Sql for a bit but found it a bit lacking (As it was new, go figure) and decided to go forward with Entity Framework due to the fact that I really like Linq, and although LLBLGEN had Linq integration, I figured the Entity Framework would be the first out there with any changes in Linq. (Not exactly sage like foresight) And at the time HQL was still the thing for NHibernate, and although it's not a bad design, it's a nightmare waiting to happen since you can't get a compile time check on the HQL strings. So it seemed like the right idea at the time, and despite what I'm about to write, it may still be.</p>
<p>I saw a lot of people bagging on it saying that it was missing this feature or that feature. Most people were annoyed that there wasn't built in lazy loading. Some were annoyed with the fact that the classes are coupled to persistence. Others just complained because it wasn't [insert your ORM here]. I on the other hand championed the cause with this in mind:</p>
<p><strong>It's just a framework. The tools are there do what you need, you just need to build it.</strong></p>
<p>Take as is, the word framework is just that. It's just a start. It's that point where a house is just a bunch of wood nailed togther. You can't really live in it as is... well I suppose you could?... but it has what you need to produce a complete house. Just takes a little time and effort. You can already see where this is going. After all, <a href="http://byatool.com/index.php/pontification/programmer-hero-to-all-or-digital-masochist/">I've already figured out I like pain.</a></p>
<p>So the first issue I ran into was the context itself. You see, I was already used to multiple calls to the database being done with one "connection" and by that I mean not this every time I wanted to get something:</p>
<pre>  <span style="color: #0000ff;">using</span>(<span style="color: #0000ff;">var</span> entity <span style="color: #0000ff;">as</span> <span style="color: #008080;">ToolEntities</span>)
  {
    entity.Tools.Select(...)
  }</pre>
<p>Mind you my syntax is more psuedo in that example, but the idea was simple; It was going to be annoying to have to do that every time I wanted something from the database. So after hours of thought and some research,<a href="http://byatool.com/index.php/pontification/singleton-objectcontext-the-remix/"> I came up with a solution</a> that would open one "connection" per request that all queries within that request would use. Ok so that was out of the way, and I can't compain since after all:</p>
<p><strong>It's just a framework. The tools are there do what you need, you just need to build it.</strong></p>
<p>The next thing I ran into was lazy loading a many to one or one to one property. I had already seen stuff on many to many or one to many loading. Simple method .Load(). To my surprise there wasn't such a method for this (Not directly at least) so I was stumped. Time to go back to LLBLGEN? Hell no, mush on. And mush on I did. I found the .Include method:</p>
<pre>  context.Tools.Include(<span style="color: #800000;">"Favorites"</span>)</pre>
<p>Boo yah, and I'm back in the game... or was for a little bit until I realized that this is pretty bad since Include loads the whole object you are including. This could be ridiculous if you have an object with 10... 100... ONE MILLION many to one or one to one properties. So once again, hours of thought and research later <a href="http://byatool.com/index.php/pontification/entity-framework-possible-lazy-loading-solution/">I came up with a solution</a> that was eh good enough but wasn't exactly what I'd hoped for.</p>
<p><strong>It's just a framework. The tools are there do what you need, you just need to build it.</strong></p>
<p>Another issue I ran into was a creating an IN clause method. <a href="http://byatool.com/index.php/general-coding/sub-select-and-in-clause-faking/">Contains</a> just doesn't work with Entity Framework. Straight up, flat out, no can do sir. So again, with time and research I found a way to do this (Which I haven't posted yet due to the fact I didn't come up with the solution and I can't find the link I got it from). Of course there was the <a href="http://byatool.com/index.php/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/">order by situation</a>, <a href="http://byatool.com/index.php/net-issues/a-relationship-is-being-added-or-deleted-from-an-associationset-with-cardinality-constraints-a-corresponding-must-also-be-added-or-deleted/">oh and this gem</a>, <a href="http://byatool.com/index.php/lessons/entity-framework-odd-things-during-querying">and this</a> that I can only describe as a god damned mess. Really? It's in the context yet you still have to run a query on it? Really??</p>
<p>I'm not going to quit on Entity Framework just yet but after a little introspection I have to admit that I'm close to responding to my own righteous:</p>
<p><strong>It's just a framework. The tools are there do what you need, you just need to build it.</strong></p>
<p>With a big :</p>
<p><strong>Go f- yourself.</strong></p>
<p>This whole situation reminds me of a saying:</p>
<blockquote><p>If you're in a poker game and you can't figure out who the patsy is, you're the patsy.</p></blockquote>
<p>It doesn't take much imagination to apply that saying to my situation and to be honest I might be falling into the same situation with the MVC framework. Time will only tell with that. Although at least with MVC I have plenty of patsies with me. I think with Entity Framework, I might be the only one losing money.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/" title="Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types">Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Entity Framework: LINQ to Entities only supports casting Entity Data Model primitive types</title>
		<link>http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/</link>
		<comments>http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 17:11:19 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[.Net Issues]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=731</guid>
		<description><![CDATA[So in typical tool fashion I posted this little gem without realizing a glaring error... the order by clause. The whole idea is to create a method that can get a collection, sort it, then grab a certain number for paging. The issue was this: Expression&#60;Func&#60;K, IComparable&#62;&#62; orderBy The problem comes in when the entire [...]]]></description>
			<content:encoded><![CDATA[<p>So in typical tool fashion I posted this <a href="http://byatool.com/index.php/c/entity-framework-reusable-paging-method/">little gem</a> without realizing a glaring error... the order by clause. The whole idea is to create a method that can get a collection, sort it, then grab a certain number for paging. The issue was this:</p>
<pre>    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;K, <span style="color: #008080;">IComparable</span>&gt;&gt; orderBy</pre>
<p>The problem comes in when the entire expression is run, meaning when Entity Frame work takes:</p>
<pre>    context.Select(selectMethod).Where(whereClause).OrderBy(orderBy).ToList();</pre>
<p>and creates SQL out of it. Entity Framework doesn't really know how to handle IComparable as it has not primitive/sql type to match to it. Why it can't see the underlying type of say DateTime, no idea, but this is life.</p>
<p>So this should be an easy fix, right? Eh... yeah. First I thought instead of IComparable I could just convert to some kind of primitive type so that the EF could be on it's merry. Not so much. Turns out this probably isn't possible.</p>
<p>Well thanks to a push from <a href="http://stackoverflow.com/users/137624/ben-m">Ben M</a> at <a href="http://stackoverflow.com/questions/1145847/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primit">The O Flow</a> I got to thinking about how to attack this. Instead of sending in an expression for the order by, why not send in a method that would take in a query and tell it how to order itself. Sounds hard right? (If not then you're obviously too cool for this school) Well it's not, just a different way to think about it.</p>
<p>Right off the bat, the change to the method signature would look like this:</p>
<p>Old order by parameter signature:</p>
<pre>    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;K, <span style="color: #008080;">IComparable</span>&gt;&gt; orderBy</pre>
<p>New order by parameter signature:</p>
<pre>    <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">IQueryable</span>&lt;T&gt;, <span style="color: #008080;">IOrderedQueryable</span>&lt;T&gt;&gt; orderBy</pre>
<p>So what does that mean? It means that I am going to supply the method with a method that will take in a query and return an ordered query... well not ordered yet per se but the blueprint on how to order when that time comes around. Now here's how that's used:</p>
<p>First you need the query:</p>
<pre>    <span style="color: #0000ff;">var</span> initialQuery = query
    .Where
    (
        somethingEqualsSomething
    );</pre>
<p>Then you apply the orderby method, and in the case of the original paging method, the paging too:</p>
<pre>    <span style="color: #0000ff;">var</span> orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();</pre>
<p>So overall, doesn't look too much different. Just instead of supplying the OrderBy method with a Func, you give a method that creates an ordered query.</p>
<p>How would you use this? Remember the signature was (whereClause, selectClause, orderBy, pageNumber, numberToShow, realPage, totalCountOfPages)</p>
<pre>    Tools.GetListForGrid
    (
      tool =&gt; tool.EntityId == userId,
      tool =&gt; <span style="color: #0000ff;">new</span> { Name = tool.Name },  <span style="color: #008000;">//Select Clause, I'll get to that next
      </span>toolOuter =&gt; toolOuter.OrderBy(toolInner =&gt; toolInner .Name),  <span style="color: #008000;">//OrderBy</span>
      ...
    )</pre>
<p>Two things you might notice. One would be the OrderBy signature:</p>
<pre>   toolOuter =&gt; toolOuter.OrderBy(toolInner =&gt; toolInner .Name),</pre>
<p>What the hell? Remember the method you are sending takes in a query and returns an ordered query. toolOuter is your query, toolOuter.OrderBy(toolInner =&gt; toolInner .Name) is your blueprint (IOrderedQueryable) on how it should be queried.</p>
<p>Second thing is that when I showed how to use the OrderBy method above:</p>
<pre>    <span style="color: #0000ff;">var</span> orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();</pre>
<p>I didn't include the select clause. Partially because I didn't want to complicate it yet, partially because it has it's own issue. If you're like me, you use the <a href="http://byatool.com/index.php/lessons/beyond-the-wall/">select clause a lot</a>. Why? Because it limits the amount of information you take from the database. Say if you are trying to fill a drop down list, why select an entire Tool object (Which could have a ton of mapped properties) when all you need is Id and Name? Seems silly. That's where the Select clause comes in. Now the issue is where to put the order by. You would think after the select clause, since you want to sort on only what you are selecting. Problem is, with paging that gets screwed up. The way sql server "pages" is that it selects twice.</p>
<p>Select all the things that match this where clause.<br />
Select a certain number of items from that starting at X.</p>
<p>The first select creates a dataset with row numbers, and the second one selects the items based on those row numbers. IE take 5 starting at row 5. Now the way the EF handles the order by is to grab the info you need from the Select (Ordered by something... you don't get to choose) and THEN order and grab. As you can guess this may not give the needed results. So how can this be solved? Order before the select as witnessed in the new and improved method:</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IList</span>&lt;K&gt; <span style="color: #000000;">GetListForGrid</span>&lt;T, K&gt;
(
    <span style="color: #0000ff;">this</span> ObjectQuery&lt;T&gt; query,
    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;T, <span style="color: #008080;">Boolean</span>&gt;&gt; somethingEqualsSomething,
    <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;T, K&gt;&gt; selectClause,
    <span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">IQueryable</span>&lt;T&gt;, <span style="color: #008080;">IOrderedQueryable</span>&lt;T&gt;&gt; orderBy,
    <span style="color: #008080;">Int32</span> pageNumber,
    <span style="color: #008080;">Int32</span> numberToShow,
    <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> realPage,
    <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> totalCountOfPages
)
{
    <span style="color: #008080;">IList</span>&lt;K&gt; returnValue;

    <span style="color: #008080;">Int32</span> totalItemCount =
        query
        .Count
        (
          somethingEqualsSomething
        );

    totalCountOfPages = Methods.TotalCountOfPages(totalItemCount, numberToShow);
    realPage = Methods.GetRealPage(totalCountOfPages, pageNumber);

    <span style="color: #0000ff;">var</span> initialQuery =
      query
      .Where
      (
        somethingEqualsSomething
      );

   <span style="color: #0000ff;">var</span> orderedQuery = orderBy(initialQuery);

    returnValue = orderedQuery
      .Select
      (
        selectClause
      )
      .Skip(numberToShow * realPage)
      .Take(numberToShow)
      .ToList();

      <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>And usage:</p>
<pre>    Tools.GetListForGrid
    (
       tool =&gt; tool.Id == userId,
       tool =&gt; new { Name = tool.Name },  <span style="color: #008080;"><span style="color: #008000;">//Select Clause</span>
</span>       toolOuter =&gt; toolOuter.OrderBy(toolInner =&gt; toolInner .Name),  <span style="color: #008000;">//OrderBy</span>
       pageNumber,
       amountToShow,
       out realPage,
       out totalCountOfPages
    );</pre>
<p>Now this one actually works with Entity Framework and not just Linq to objects like the last one.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/" title="ASP.Net MVC: Upload Image to Database and Show Image &#8220;Dynamically&#8221; Using a View">ASP.Net MVC: Upload Image to Database and Show Image &#8220;Dynamically&#8221; Using a View</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Reusable Paging Method</title>
		<link>http://byatool.com/c/entity-framework-reusable-paging-method/</link>
		<comments>http://byatool.com/c/entity-framework-reusable-paging-method/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 21:47:48 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Paging]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=724</guid>
		<description><![CDATA[OBSOLETE... sort of. Found an issue with this and am posting the issue today. (07/21/2009) A while back I decided to show some paging stuff and I forgot that recently, well ok in the last few months, I actually put together a sort of generic extension method to take care of most of the paging [...]]]></description>
			<content:encoded><![CDATA[<p><strong><a href="http://byatool.com/index.php/net-issues/entity-framework-linq-to-entities-only-supports-casting-entity-data-model-primitive-types/">OBSOLETE... sort of. Found an issue with this and am posting the issue today. (07/21/2009)</a></strong></p>
<p>A while back <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">I decided to show some paging stuff</a> and I forgot that recently, well ok in the last few months, I actually put together a sort of generic extension method to take care of most of the paging situations I was running into. Reason being is I got tired of writing the same method over and over. I figured I'd share it in hopes that somehow, somewhere, it would keep someone's dream alive. That and I figured I needed to make up for not posting for a while... which to some of you might have been a good thing.</p>
<p>Anywho, it's not to difficult actually. Small note though, when reading the code you will see the <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">TotalCountOfPages method</a> and the <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">GetRealPage method</a>. If you can't figure out what those are then I just don't know what to do. (HINT: They are linked somewhere in this very post! Side note: This post is on track to match the normal self linking per post quota on <a href="http://www.codinghorror.com/blog/archives/001282.html">atypical Codding Horror post</a>)</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IList</span>&lt;K&gt; GetListForGrid&lt;T, K&gt;
(
  <span style="color: #0000ff;">this</span> <span style="color: #008080;">ObjectQuery</span>&lt;T&gt; query,  <span style="color: #008000;">//Extension method syntax... basically takes in any SomeEntities.SomeTableRepresentation</span>
  <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;T, <span style="color: #008080;">Boolean</span>&gt;&gt; somethingEqualsSomething,  <span style="color: #008000;">//Where clause</span>
  <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;T, K&gt;&gt; selectClause,
  <span style="color: #008080;">Expression</span>&lt;<span style="color: #008080;">Func</span>&lt;K, <span style="color: #008080;">IComparable</span>&gt;&gt; orderBy,  <span style="color: #008000;">//Turns out order by just <a href="http://byatool.com/index.php/general-coding/orderby-using-a-property-name/">needs anything that is IComparable</a></span>
  <span style="color: #008080;">Int32</span> pageNumber,
  <span style="color: #008080;">Int32</span> numberToShow,
  <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> realPage,
  <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> totalCountOfPages
)
{
   <span style="color: #008080;">IList</span>&lt;K&gt; returnValue;
   <span style="color: #008000;">//Get the total count of the items.  Need this to do proper paging.</span>
   <span style="color: #008080;">Int32</span> totalItemCount =
      query
      .Count
      (
         somethingEqualsSomething
      );

   totalCountOfPages = TotalCountOfPages(totalItemCount, numberToShow);
   realPage = GetRealPage(totalCountOfPages, pageNumber);

   returnValue = query
   .Where
   (
      somethingEqualsSomething
   )
   .Select
   (
      selectClause
   )
   .OrderBy(orderBy)
   .Skip(numberToShow * realPage)
   .Take(numberToShow)
   .ToList();

   <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>As you can see there are a lot of expressions going on and that's the way this works. It takes care of the annoying stuff that you would have to copy an paste while you supply it the stuff that changes like what you want to select and what the needed items have to match to be selected. Even has something for an order by. What the usage look like?</p>
<pre>  ToolEntities.Tools.GetListForGrid
  (
    something =&gt; something.SomethingId == passedInSomethingId,  <span style="color: #008000;">//Where clause
</span>    found =&gt; found,  <span style="color: #008000;">//Select: Simple here.  Usually I use classes to hold info... next post</span>
    found =&gt; found.Name,  <span style="color: #008000;">//Order by</span>
    pageNumber,
    amountToShow,
    <span style="color: #0000ff;">out</span> realPage,
    <span style="color: #0000ff;">out</span> totalCountOfPages
  );</pre>
<p>Really simple, eh?</p>
<p>Why totalCountOfPages and RealPage out? Well the whole idea is that this infomation is valuable to the picker control you will be constructing outside this method call. RealPage is nice for showing what page the pager is on and how to figure out what the previous and next pages will be. TotalCountOfPages is useful for the last page possible. Now the nice thing about the RealPage method is that it won't give you a non existent page. It will only give you the best possible page if the pageNumber parameter is over the possible amount of pages.</p>
<p>Also do notice that this is an extention method meant to be used with the Entity Framework's built in system of handling the Table representations say ToolEntities.Tools.(Method will show up here in intellisense). This makes it cleaner to me than having to pass in the actual current context. As in:</p>
<p>GetListForGrid(ToolEntities.Something, ...) vs ToolEntites.Something.GetListForGrid(...)</p>
<p>In the end, either way is fine.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-1/" title="Paging and the Entity Framework, Skip, and Take Part 1">Paging and the Entity Framework, Skip, and Take Part 1</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/c/entity-framework-reusable-paging-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Possible Lazy Loading Solution</title>
		<link>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/</link>
		<comments>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 14:53:02 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=713</guid>
		<description><![CDATA[So been a while since I posted last, and I'm sure everyone has been worried. Turns out that I've been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I've been working one, [...]]]></description>
			<content:encoded><![CDATA[<p>So been a while since I posted last, and I'm sure everyone has been worried. Turns out that I've been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I've been working one, I forced myself to tackle Lazy Loading in the Entity Framework. Turns out the solution isn't that hard since it has everything needed to make it work.</p>
<p>One of the biggest waaaaahbumlance calls is the fact that Entity Framework doesn't have lazy loading. This isn't true. It does, you just have to do a little work, which is to be expected from a FRAMEWORK. Now I have to admit, I wish there were a slightly less odd way of doing this, but eh it's not too bad.</p>
<p>Say you have a class named Topic and it has a reference to a Forum class named ParentForum. Now this is just a property on the actual class created by the E-Work to represent a many to one foriegn key relationship between the Topic table and the Forum table. Now the problem comes in when you try to use something from that property like:</p>
<pre>    <span style="color: #008080;">Int32</span> someInt = topic.ParentForum.ForumId;</pre>
<p>If you didn't use the Include method when you got that topic:</p>
<pre>    context.Include(<span style="color: #800000;">"ParentForum"</span>).Select(topic =&gt; topic);</pre>
<p>You are screwed because the ParentForum property will return a null. So this forces you to use Include every time you want to get a Topic and access it's ParentForum property. Sucks.</p>
<p>So next thought is to find out how to lazy load and then plunk it into that generated property. Eh I don't know about you, but that sounds like a bad idea to mess around with a generated file. You have no idea when the E-Work will just trash the file and rebuild.</p>
<p>Next thought was to create a proxy property to check the real one and then load if it's not already loaded. Something like:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Forum</span> ParentForumLazyLoaded
    {
        <span style="color: #0000ff;">get</span>
        {
           <span style="color: #008000;">//check and return</span>
        }
    }</pre>
<p>Ok so that's not horrible except two things: The name looks dumb and people can still get at the original ParentForum property.</p>
<p>So in comes my solution and it's pretty simple. Rename the property name on the class to something ParentForumInner and make it private.</p>
<pre><img class="alignnone size-full wp-image-714" title="bat_lazyload1" src="http://byatool.com/wp-content/uploads/2009/06/bat_lazyload1.jpg" alt="bat_lazyload1" width="598" height="263" /></pre>
<p>Then you can create a much nicer outward facing property like:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Forum</span> ParentForum
    {
      <span style="color: #0000ff;">get</span>
      {
          <span style="color: #0000ff;">if</span> (!ParentForumInnerReference.IsLoaded)
          {
              ParentForumInnerReference.Load();
          }

        <span style="color: #0000ff;">return</span> ParentForumInner;
    }
    <span style="color: #0000ff;">set</span>
    {
        ParentForumInner = <span style="color: #0000ff;">value</span>;
    }
}</pre>
<p>Now one of the issues with this is that although outside the class only the ParentForum property can be seen, within the class they both can be seen which can lead to issues like:</p>
<pre>    context.Topics.Where(topic =&gt; topic.ParentForum.ForumId == id);  <span style="color: #008000;">//boom</span></pre>
<p>Where you should be using:</p>
<pre>    context.Topics.Where(topic =&gt; topic.ParentForumInner.ForumId == id);  <span style="color: #008000;">//yay</span></pre>
<p>E-Work doesn't know how to handle that situation when evaluating that expression and the kicker is that it does just fine compile time. You won't know this is bad until runtime.</p>
<p>Other issue is that you have to do a little more work then just some setting on the property which is what most people wish for. I guess that may be true, but again this is a framework. It gives you all the tools you need to makes things work, you just have to do some coding.</p>
<p>The plus side to this is that with minimal coding, you can completely get rid of Include which to me is huge.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/add-on/random-add-on-automapper/" title="Random Add-On &#8211; Automapper">Random Add-On &#8211; Automapper</a></li><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework, Include, and Data Item classes</title>
		<link>http://byatool.com/lessons/entity-framework-include-and-data-item-classes/</link>
		<comments>http://byatool.com/lessons/entity-framework-include-and-data-item-classes/#comments</comments>
		<pubDate>Thu, 14 May 2009 14:33:27 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=694</guid>
		<description><![CDATA[So found something interesting out the other day, and maybe you already knew this but I didn't so I'm going to post about it. Don't like it? Too bad. One things nice about the Entity Framework is the ability to create or fill a class on the fly with the Linq query methods/language. You.. you [...]]]></description>
			<content:encoded><![CDATA[<p>So found something interesting out the other day, and maybe you already knew this but I didn't so I'm going to post about it.  Don't like it?  Too bad.</p>
<p>One things nice about the <span class="showItLink" xmlns:comment="And really NHibernate does this too... I would assume LLBLGEN also.">Entity Framework</span> is the ability to create or fill a class on the fly with the Linq query methods/language. You.. you have no idea what I'm trying to say. Fine. I'll put it in programming speak:</p>
<pre>  someList.Select(item =&gt; <span style="color: #0000ff;">new</span> { item.Name, item.ID })

  or

  <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> someList
  <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> { item.Name, item.ID }</pre>
<p>OR</p>
<pre>  someList.Select(item =&gt; <span style="color: #0000ff;">new</span> DataItemClass { Name = item.Name, ID = item.ID })

  or

  <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> someList
  <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> DataItemClass { Name = item.Name, ID = item.ID }</pre>
<p>As you can see, they are two slightly different examples. One will create a list of anonymous types and the other a list of DataItemClass objects. Now that's not really the point of this, the point is something like this:</p>
<pre>  context.Topics
    .Select(topic =&gt;
                <span style="color: #0000ff;">new</span> TopicItem
                {
                  TopicName = topic.Name ,
                  Creator = topic.User.UserName,
                  Category = topic.Category.Description
                }
              )</pre>
<p>Now, here's the thing that I assumed. When you select out a bunch of topics and you want to make sure that the one to on properties are "include"ed like thus:</p>
<pre>  topicList
   .Include(<span style="color: #800000;">"User"</span>)
   .Include(<span style="color: #800000;">"Category"</span>)
   .Select(item =&gt; item);</pre>
<p>Other wise when you try to access that User property  <span class="showItLink" xmlns:comment="This is unless the Context already has that user in memory, but you can't count on that.">you'll get a null reference exception</span>. So with this I thought that when you query like I did above to fill the TopicItem object, I would get the same problem as I would if I tried just accessing the property on a hydrated Topic. In other words:</p>
<pre>  Creator = topic.User.UserName,</pre>
<p>Would blow up mid query after all calling that property after a query would sans include. Come to find out, and I probably should have already known this, Entity Framework is just fine without having to have the Include method or any kind of join. Infact, adding the include method in the method chain:</p>
<pre>  context.Topics
    .Include(<span style="color: #800000;">"User"</span>)
    .Include(<span style="color: #800000;">"Category"</span>)
    .Select(topic =&gt;
                <span style="color: #0000ff;">new</span> TopicItem
                {
                  TopicName = topic.Name ,
                  Creator = topic.User.UserName,
                  Category = topic.Category.Description
                }
              )</pre>
<p>Did nothing when I profiled the query. The SQL was exactly the same with or without the include. So it's smart enough to know that if I am not actually hydrating an entire Topic object, it doesn't need to bother with the includes. Go figure.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-include-and-data-item-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Just Use the Stupid Functionality</title>
		<link>http://byatool.com/pontification/just-use-the-stupid-functionality/</link>
		<comments>http://byatool.com/pontification/just-use-the-stupid-functionality/#comments</comments>
		<pubDate>Mon, 11 May 2009 15:22:34 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Optimization]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=685</guid>
		<description><![CDATA[So something I've come across time and time again since starting to use ORMs (about 3 or so years ago) was the infamous "hydrate a reference object just to save another." If you haven't had this before, you probably will anyhow, but here's what it is. Say I have a "Manny" object and I need [...]]]></description>
			<content:encoded><![CDATA[<p>So something I've come across time and time again since starting to use ORMs (about 3 or so years ago) was the infamous "hydrate a reference object just to save another." If you haven't had this before, you probably will anyhow, but here's what it is. Say I have a "Manny" object and I need to assign some kind of "fertility drug type" to it. Now this "fertility drug type" is basically representative of a table that has an id and description and nothing else really. Now the question is, if I know the ID of "HCG" is 1, should I bother even getting it from the database? I mean after all:</p>
<pre>  <span style="color: #008080;">Drug</span> totallyNotUsingVitamins = toolContext.Drugs.Select(drug =&gt; drug.Name == <span style="color: #800000;">"HCG"</span>);
  manny.DrugOfChoice = totallyNotUsingVitaminS;</pre>
<p>Looks pointless when I can do this:</p>
<pre>  playersObject.DrugTypeReference.EntityKey =
     <span style="color: #0000ff;">new</span> <span style="color: #008080;">EntityKey</span><span style="color: #800000;"><span style="color: #000000;">(</span>"ToolEntities.BallPlayers"</span>, <span style="color: #800000;">"drugOfChoiceID"</span>, 1);</pre>
<p>Which was taken from <a href="http://blogs.msdn.com/alexj/archive/2009/03/25/tip-7-faking-foreign-key-properties-in-net-3-5-sp1.aspx">here.</a></p>
<p>So here's the problem: Why should I have to hit the database if I know what the ID is? I mean, that's a trip I don't have to make right?</p>
<p>If you're asking that question, then it's possible you don't understand how a lot of ORMs work, or in this site's case: The Entity Framework.</p>
<p>What it really comes down to a couple arguments:</p>
<ul>
<li>What is the cost if it hits the database?</li>
<li>Is it actually hitting the database?</li>
<li>It's just easier to set the ID</li>
</ul>
<p><strong>What is the cost if it hits the database?</strong></p>
<p>Now the first one you could almost make an argument, after all what's the point of hitting it if you don't need to? This might seem silly:</p>
<pre>  <span style="color: #0000ff;">using</span>(<span style="color: #008080;">ToolEntities</span> toolContext = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ToolEntities</span>())
  {
    <span style="color: #008080;">Drug</span> totallyNotUsingVitamins = toolContext.Drugs.Select(drug =&gt; drug.Name == <span style="color: #800000;">"HCG"</span>);
    manny.DrugOfChoice = totallyNotUsingVitaminS;
  }</pre>
<p>If that is the only time you're using this. A one off like that does seem to beg overdoing it. But really is it? This is probably the strongest argument for the straight ID set and really what is the real cost? In order to persist the object, a connection has to be created and the entity has to be persisted. So in reality, you have to create a connection any how, so the actually getting and hydrating of the reference object is just sort of tagged onto that and unless there is something wrong with the table or connection, this adds a minimal amount of time.</p>
<p><strong>Is it actually hitting the database?</strong></p>
<p>But what if this has to be run a million times? Then what? I have to get that item a million times and now my hits have gone from one million to two million?</p>
<pre>  <span style="color: #0000ff;">using</span>(<span style="color: #008080;">ToolEntities</span> toolContext = <span style="color: #0000ff;">new</span> <span style="color: #008080;">ToolEntities</span>())
  {
    <span style="color: #0000ff;">for</span>(<span style="color: #008080;">Int32</span> loopCounter = 0; loopCounter &lt; someNumber; loopCounter ++)
    {
      <span style="color: #008080;">Drug</span> totallyNotUsingVitamins = toolContext.Drugs
                                       .Select(drug =&gt; drug.Name == <span style="color: #800000;">"HCG"</span>)
                                       .First();
      manny.DrugOfChoice = totallyNotUsingVitaminS;
    }
  }</pre>
<p>Ok not the best example, but the point is that within that using you will be updating a million records which you would assume that</p>
<pre>  <span style="color: #008080;">Drug</span> totallyNotUsingVitamins = toolContext.Drugs.Select(drug =&gt; drug.Name == <span style="color: #800000;">"HCG"</span>);</pre>
<p>Would be run a possible two million times. You could make the argument that Entity Framework does make a select against the database even if the <a href="http://stackoverflow.com/questions/543587/entity-framework-why-does-the-database-get-hit-if-the-data-is-in-the-context">object is in the context</a>. This is something I've thought rather odd myself. However, it's just a query on an already open connection. <a href="http://msdn.microsoft.com/en-us/library/cc853327.aspx">And since creating the query is done the first time around, the acutal query being run is minimal in effort</a>.  Basically the hard work was does the first time around. The next time is nothing to really consider.  </p>
<p><strong>It's just easier to set the ID</strong></p>
<p>Ok so this one is hard to discredit since it is easier. It's about one line less easier. Is one line really worth this? Is it worth the ease of understanding? From the first example, it's pretty easy to understand what I'm setting. Select a drug type of "HCG". Second one, not so much. All I see is an ID, so if I want to know what drug that is, I'd have to go searching for what that ID is. Also, from a spec level, it's more clear to say:</p>
<blockquote><p>Set DrugOfChoice to "HCG"</p></blockquote>
<p>Then</p>
<blockquote><p>Set DrugOfChoice to 1</p></blockquote>
<p>Now I may be reaching on this last example, but as I said, it will be hard to prove that the second example isn't "easier" coding wise. After all it's one less line. However, when things like readablity comes in, I can't see the second being a winner in that contest.</p>
<p>Once a person understands how an ORM like the Entity Framework works, it becomes apparent that some of the old ways of thinking need to be abandoned as in the long run they only hold overall development back. And beyond that, sometimes when we think we're optimizing, we could actually doing more harm than needed. Losing readability for the sake of ridiculously small amounts of time just doesn't make sense anymore.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/just-use-the-stupid-functionality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paging and the Entity Framework, Skip, and Take Part 3</title>
		<link>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/</link>
		<comments>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/#comments</comments>
		<pubDate>Fri, 08 May 2009 14:30:50 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Skip]]></category>
		<category><![CDATA[Take]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=635</guid>
		<description><![CDATA[Get the total count of pages. &#124; Get the real page number. &#124; Using Skip and Take to Page &#124; The Actual Paging Controls Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">Get the total count of pages.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">Get the real page number.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">Using Skip and Take to Page</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-4">The Actual Paging Controls</a></p>
<p>Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to Linq, the Entity Framework, and well that's it I think.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IList&lt;ToolItem&gt;</span> GetSomeTools(<span style="color: #008080;">String</span> name, <span style="color: #008080;">Int32</span> numberToShow, <span style="color: #008080;">Int32</span> pageNumber, <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> realPage, <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> totalCountOfPages)
{
  <span style="color: #008000;">//EntityContext.Context is just a </span><a href="http://byatool.com/index.php/lessons/entity-framework-objectcontext-observations-on-caching"><span style="color: #008000;">singletonish version</span></a><span style="color: #008000;"> of the
  //Entities class.  Most people would use
  //  using (ToolEntities context = new ToolEnties())
</span>  <span style="color: #008080;">Int32</span> totalCount = EntityContext.Context.ToolItems
		   .Count(item =&gt; item.Name == name);
  <span style="color: #008000;">//This is the method from the first post of this series
  //Just getting the count of pages based on numberToShow and
  //item totalCount</span>
  totalCountOfPages = TotalCountOfPages(totalCount, numberToShow);
  <span style="color: #008000;">//This is the method from the second post of this series
  //Basically getting the best possible page if the page number
  //is higher than the totalCountOfPages or lower than 0</span>
  realPage = GetRealPage(totalCountOfPages, pageNumber);

  returnValue = EntityContext.Context.ChatRooms
			  .Where(item =&gt; item.Name == name )
			  .OrderBy(item =&gt; item.Name)
			  .Skip(numberToShow * realPage)
			  .Take(numberToShow)
			  .ToList();

  <span style="color: #0000ff;">return</span> returnValue.ToList();
}</pre>
<p>Really simple yes? It follows like this:</p>
<p>Say I'm on page 1, which for this would be zero or pageNumber - 1. So I want to grab the first 20 items from the database. Well that means I want to start at 0 and grab 20. Now if you want this all to be done with some kind of conditional thing that either handles the first page or the other pages, you actually want to skip the same way no matter what the page number is. This is taken care of by numberToShow * realPage since even at 0 this works. After all 0 * anything is 0 and therefore you will be Skipping 0 items. So in other words, you're at the start. Next you want to Take the amount of items you need, which is 20. Next time around you'll start at 20 Skip(numberToShow 20 * realPage 1) and take the next 20. Nice thing is, even if you say Take 20 and there are only 2 left, it doesn't care. It will just grab those two.</p>
<p>And there you have it, how to page with the Entity Framework and minimal amount of work. I know I hate taking other people's methods (Like the TotalCountOfPages and GetRealPage methods), don't know why. So sorry if I am forcing you to do so. However, the two methods I gave are semi important to this.</p>
<p>You might wonder why realPage and totalCountOfPages, well this is useful stuff when knowing what page is next for paging controls.  Next post I'll show those off but I'll warn you, they are nothing spectacular.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/use-linq-to-split-a-list-skip-and-take/" title="Use Linq to Split a List: Skip and Take">Use Linq to Split a List: Skip and Take</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paging and the Entity Framework, Skip, and Take Part 1</title>
		<link>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-1/</link>
		<comments>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-1/#comments</comments>
		<pubDate>Wed, 06 May 2009 13:41:44 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Paging]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=620</guid>
		<description><![CDATA[Get the total count of pages. &#124; Get the real page number. &#124; Using Skip and Take to Page &#124; The Actual Paging Controls So something I've been doing a lot of lately is making quite possibly the best thing ever: String cheese wrapped in turkey bacon. But when I'm not doing that, I am [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">Get the total count of pages.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">Get the real page number.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">Using Skip and Take to Page</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-4">The Actual Paging Controls</a></p>
<p>So something I've been doing a lot of lately is making quite possibly the best thing ever: String cheese wrapped in turkey bacon. But when I'm not doing that, I am working with a lot of ListViews and the entity framework. Now I know there are "built in" paging controls but I just haven't liked what I've seen. So I took it upon myself one day to develop a repeatable system for paging. Say you have users and a bunch of invites that are attached to the users. You want to show a list of invites for a particular user, but you want a ListView that doesn't show every invite... ie you need a pager. Well just so happens I have a solution, but as always you should consult a doctor before use.</p>
<p>First off you need a method to get the total count of pages meaning what the ceiling is when you page upwards. After all, if you go over the possible count of pages, you'll just get no items returned and look kind of dumb.</p>
<p>There are three situations you have to look out for: You have less items that the required items per page (Say 10 rows but you display 20 row per page), you have a perfect division (20 rows and 20 row per page or 40 rows and 20 rows per page, ect), you have an uneven division (21 rows and 20 rows  per page). First two are easy, third isn't hard exactly but there are some catches.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">Int32</span> TotalCountOfPages(Int32 rowCount, Int32 neededPageSize)
{
<span style="color: #008080;">  Int32</span> returnValue;
<span style="color: #0000ff;">  if</span>(rowCount &gt; 0)
  {
    <span style="color: #0000ff;">if</span> (rowCount &lt;= neededPageSize)
    {
      returnValue = 1;
    }
    <span style="color: #0000ff;">else</span>
    {
      <span style="color: #0000ff;">if</span> ((rowCount % neededPageSize) == 0)
      {
        returnValue = rowCount / neededPageSize;
      }
      <span style="color: #0000ff;">else</span>
      {
        <span style="color: #008080;">Decimal</span> convertedPageSize =
         Convert.ToDecimal(neededPageSize);
        <span style="color: #008080;">Decimal</span> convertedRowCount =
         Convert.ToDecimal(rowCount);
        <span style="color: #008080;">Decimal</span> resultRounded =
          Math.Round(convertedRowCount / convertedPageSize);
        <span style="color: #008080;">Decimal</span> resultNonRounded =
          convertedRowCount / convertedPageSize;

        <span style="color: #0000ff;">if</span> (resultRounded &lt; resultNonRounded)
        {
           returnValue =
            Convert.ToInt32(resultRounded + 1);
        }
        <span style="color: #0000ff;">else</span>
        {
           returnValue =
            Convert.ToInt32(resultRounded);
        }
      }
    }
  }
<span style="color: #0000ff;">  else
</span>  {
    returnValue = 0;
  }
  <span style="color: #0000ff;">return</span> returnValue;
}</pre>
<p>Ok so first off, I assume this one is pretty obvious:</p>
<pre><span style="color: #0000ff;">  if</span>(rowCount &gt; 0)</pre>
<p>If there aren't any rows, the there can't be a page count.</p>
<p>Next take care the less rows than being shown per page:</p>
<pre>  <span style="color: #0000ff;">if</span> (rowCount &lt;= neededPageSize)
  {
    returnValue = 1;
  }</pre>
<p>Simple enough. Now for the second part, a perfect division between rows and rows to show:</p>
<pre> <span style="color: #0000ff;">if</span> ((rowCount % neededPageSize) == 0)
 {
    returnValue = rowCount / neededPageSize;
 }</pre>
<p>Basically, for those who don't know mod or the % operator, that means there is no remainder. If there were, the result of rowCount % neededPageSize would not be 0 since Mod basically means "Give me what's left over when I divide something by something else."</p>
<p>Ok, this is where it gets a little messy as I have yet to find a good way to round a number up since, far as I know, there's no way to do it with the .Net lib'ary. So, I had to come up with something clever... and when that failed I came up with this:</p>
<pre> <span style="color: #008080;">Decimal</span> convertedPageSize =
    Convert.ToDecimal(neededPageSize);
 <span style="color: #008080;">Decimal</span> convertedRowCount =
    Convert.ToDecimal(rowCount);
  <span style="color: #008080;">Decimal</span> resultRounded =
    Math.Round(convertedRowCount / convertedPageSize);
  <span style="color: #008080;">Decimal</span> resultNonRounded =
    convertedRowCount / convertedPageSize;

  <span style="color: #0000ff;">if</span> (resultRounded &lt; resultNonRounded)
  {
      returnValue =
          Convert.ToInt32(resultRounded + 1);
  }
  <span style="color: #0000ff;">else</span>
  {
     returnValue =
       Convert.ToInt32(resultRounded);
  }</pre>
<p>Ok so what's going on here? First off, because trying to divide an integer by an integer gives me an integer, I had to covert some stuff to decimal. Why is that? When I divide them, I need to know if the number after the decimal is between 1 and 1.5 since Math.Round will round down in that case killing my ability to tell if I have enough pages.</p>
<p>Example: 19 rows and 10 per page will give me a 1.9 which Round will make 2. This is perfect since I need two pages to show the 19 rows. What if I have 14 rows and 10 per page? I get 1 from rounding. Uh oh. I really need two pages.</p>
<p>How do I get around this? Get the rounded version and the unrounded version. From there I know that if the unrounded version is greater than the rounded version I need an extra page.</p>
<p>So 14 rows / 10 per page = 1.4 unrounded and 1 rounded. 1.4 &gt; 1, so that 1 page isn't going to do it. I need to add one more page. Now if it 19 rows/10 per page I'll get 1.9 unrounded and 2 rounded. 2 pages is exactly what I need and I don't have to add anything.</p>
<p>Next post I'll show the next needed method: How to tell if the page number being sent in (From the pager/UI) is actually valid. If not, then grab the last possible amount of records.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/c/entity-framework-reusable-paging-method/" title="Entity Framework: Reusable Paging Method">Entity Framework: Reusable Paging Method</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A relationship is being added or deleted from an AssociationSet &#8230; With cardinality constraints, a corresponding &#8230; must also be added or deleted.</title>
		<link>http://byatool.com/net-issues/a-relationship-is-being-added-or-deleted-from-an-associationset-with-cardinality-constraints-a-corresponding-must-also-be-added-or-deleted/</link>
		<comments>http://byatool.com/net-issues/a-relationship-is-being-added-or-deleted-from-an-associationset-with-cardinality-constraints-a-corresponding-must-also-be-added-or-deleted/#comments</comments>
		<pubDate>Mon, 04 May 2009 14:43:32 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[.Net Issues]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=615</guid>
		<description><![CDATA[So I ran into this error yesterday trying to delete a user which in turn has multiple collections that would be deleted too. You would think that I would have to manually delete the entire User tree, on collection at a time. Well the way thing work is that Entity framework will do the work [...]]]></description>
			<content:encoded><![CDATA[<p> So I ran into this error yesterday trying to delete a user which in turn has multiple collections that would be <span class="showItLink" xmlns:comment="Say user addresses.">deleted too. </span> You would think that I would have to manually delete the entire User tree, on collection at a time. Well the way thing work is that Entity framework will do the work for you if your tables are set to Cascade Delete. Now, you might see that error and be confused as to why it crops up even when you do have Cascade Delete on the needed tables. Here's the situation:</p>
<p>As I said, I was trying to delete a user through the entity framework but noticed that all the addresses the user had were still in the database after deletion. Whoops. I dun forgot to set Cascade Delete on the tables. No big deal. So after I fixed the tables, I went to update the edmx file... ie update from database... and I thought all was well. Yeah not so much. I started to get this error. So the next thing I did was open the .edmx file in <span class="showItLink" xmlns:comment="Or Notepad ++ for that matter.">notepad</span>  and looked for "delete". Sure enough I found it.</p>
<pre>        &lt;Association Name="FK_UserAddress_User"&gt;
          &lt;End Role="ChatUser" Type="BAT.Data.Store.User" Multiplicity="1""&gt;
            &lt;OnDelete Action="Cascade" /"&gt;
          &lt;/End"&gt;</pre>
<p>Eh ok... it's there. Well after some searching I ran into <a href="http://codepolice.net/2008/12/16/cascade-delete-in-entity-framework/">this post</a>. Basically what was happening is although that shows the OnDelete Action="Cascade", it's still not everywhere it needs to be. Then it dawned on me that the way the .edmx file works is that pretty much everything has to be doubled in the file,  <span class="showItLink" xmlns:comment="The SSDL content and CSDL content areas.">once for the database and once for the actual class.</span> What was missing was the class half. For some reason when adding Cascade to a foreign key and then updating the .edmx file, only the table part of the markup gets updated. Bummer. So, what to do? Kind the foreign key name in the file (FK_UserAddress_User for example) and do a search on it. You'll find something like this:</p>
<pre>     &lt;Association Name="FK_UserAddress_User"&gt;
           &lt;End Type="BAT.Data.ChatUser" Role="User" Multiplicity="1" /&gt;</pre>
<p>Oooo right there is the problem. You see, if this were correctly done, it would have the action="delete" added to it, just like the one in the SSDL area. So how do you fix this? Manually. Hooray.</p>
<pre>     &lt;Association Name="FK_UserAddress_User"&gt;
           &lt;End Type="BAT.Data.ChatUser" Role="User" Multiplicity="1" &gt;  <span style="color: #008000;">//RIGHT HERE</span>
             &lt;OnDelete Action="Cascade"&gt;&lt;/OnDelete&gt;  <span style="color: #008000;">//RIGHT HERE</span>
           &lt;/End&gt;  <span style="color: #008000;">//RIGHT HERE</span>
     &lt;End Type="BAT.Data.UserAddress" Role="UserAddress" Multiplicity="*" /&gt;&lt;/Association&gt;</pre>
<p>As you can see, it's a simple change and you only have to do it to the object of Multiplicity="1", which of makes sense you wouldn't want a user deleted if an address is. But it's still annoying and a real pain if you have more than say one to fix.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/net-issues/a-relationship-is-being-added-or-deleted-from-an-associationset-with-cardinality-constraints-a-corresponding-must-also-be-added-or-deleted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singleton ObjectContext: The remix</title>
		<link>http://byatool.com/pontification/singleton-objectcontext-the-remix/</link>
		<comments>http://byatool.com/pontification/singleton-objectcontext-the-remix/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 18:05:05 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=502</guid>
		<description><![CDATA[I realized that when I posted this, I didn't actually post my way of solving the singleton context idea. Well it's not a real singleguy anymore in the strictest sense. It is still used by pretty much all querying BUT it is used every postback. How did I do this? With a little enginuity, brilliance, [...]]]></description>
			<content:encoded><![CDATA[<p>I realized that when I <a href="http://byatool.com/index.php/lessons/entity-framework-objectcontext-observations-on-caching" target="_blank">posted this</a>, I didn't actually post my way of solving the singleton context idea.  Well it's not a real singleguy anymore in the strictest sense.  It is still used by pretty much all querying BUT it is used every postback.  How did I do this?  With a little enginuity, brilliance, and time. (Read luck and constant pounding on the keyboard) </p>
<p>The old idea was to have a single context that was held in a static (Therefore the context was static). Couple problems:</p>
<ul>
<li>All queries and updates will be sharing this context... for every user. Hrm. I can't see anything wrong with Sally Starshine hitting the old update button and saving Dick McGurk's changes. Nothing wrong with that all.</li>
<li>Any changes to an object in the context will stay in the context until the various ways of "resetting" a static object are used, regardless of being persisted to the database. Basically, if you changed the user.UserName = "YouIdiot", "YouIdiot" will now show up anywhere you use that context... which is everywhere.</li>
</ul>
<p>So as you can see, disaster. Now, where could I have gone from here? Well insane first, then I found a solution... Page Requests. You see, when a request is made there are two events fired of importance:</p>
<pre>    <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">void</span> Application_BeginRequest(<span style="color: #0000ff;">object</span> sender, <span style="color: #008080;">EventArgs</span> e)
    {
    }

    <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">void</span> Application_EndRequest(<span style="color: #0000ff;">object</span> sender, <span style="color: #008080;">EventArgs</span> e)
    {
    }</pre>
<p>Pretty snazy, right? Well these are fired with every request, so basically these are fired every postback... and then some. The next step I took was to make context creation and tear down methods. Something like on BeginRequest: If the context doesn't exist, create and on EndRequest: If the context does exist, DESTROY. Well this worked at first... until I realized something. That cute little method BeginRequest fires on every request (Duh) meaning anytime the page requests an image. Hrm. That's a lot of useless building right? Well it occurred to me the tear down on EndRequest was a good idea since it won't do anything if the context doesn't exist. No harm no foul. The problem was the BeginRequest. Fact is, the answer was stairing at me... I already had the build up method, I just had to call it when it mattered: First use. SO can you figure out what I did? I bet you can!</p>
<pre>    <span style="color: #0000ff;">using</span> System;
    <span style="color: #0000ff;">using</span> System.Collections.Generic;
    <span style="color: #0000ff;">using</span> System.Linq;
    <span style="color: #0000ff;">using</span> System.Text;
    <span style="color: #0000ff;">using</span> System.Web;

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> EntityContext
    {
        <span style="color: #0000ff;">private</span> <span style="color: #008080;">TISQLEntities</span> _context;
        <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> MAIN_CONTEXT_KEY = <span style="color: #800000;">"MainContext"</span>;

        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">TISQLEntities</span> Context
        {
            <span style="color: #0000ff;">get</span>
            {
               <span style="color: #0000ff;">if</span> (<span style="color: #008080;">HttpContext</span>.Current.Items[MAIN_CONTEXT_KEY] == <span style="color: #0000ff;">null</span>)
                {
                    CreateContext();
                }

              <span style="color: #0000ff;">return</span> (<span style="color: #008080;">TISQLEntities</span>)HttpContext.Current.Items[MAIN_CONTEXT_KEY];
            }
        }

        <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> CreateContext()
        {
           <span style="color: #008080;">HttpContext</span>.Current.Items[MAIN_CONTEXT_KEY] = <span style="color: #0000ff;">new</span> <span style="color: #008080;">TISQLEntities</span>();
        }

        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> RemoveContext()
       {
           <span style="color: #0000ff;">if</span> (<span style="color: #008080;">HttpContext</span>.Current.Items[MAIN_CONTEXT_KEY] != <span style="color: #0000ff;">null</span>)
           {
             ((<span style="color: #008080;">TISQLEntities</span>)HttpContext.Current.Items[MAIN_CONTEXT_KEY]).Dispose();
             HttpContext.Current.Items[MAIN_CONTEXT_KEY] = <span style="color: #0000ff;">null</span>;
            }
         }
    }</pre>
<p>Idiot simple, as it would have to be coming from me. You might have seen that I'm holding it in the current HTTPContext. This is to hold the needed context for the current request. Yippee.</p>
<p>Now for the use (In the Global.asax.cs file)</p>
<pre>    <span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">void</span> Application_EndRequest(<span style="color: #0000ff;">object</span> sender, <span style="color: #008080;">EventArgs</span> e)
    {
        <span style="color: #008080;">EntityContext</span>.RemoveContext();
    }</pre>
<p>So what happens? First time I use the context:</p>
<pre>    <span style="color: #008080;">EntityContext</span>.context.SiteUser.Load();</pre>
<p>The EntityContext class creates the context and goes to town. When the request is done, the EntityContext class removes said context.</p>
<p>Now on a side not, you might notice that when doing unit tests, there is no HTTPContext. This is a problem and involves one more step (That I'm not completely happy with right now) that actually takes the old Static idea and applies it. Now you might thing that I'm undoing everything I just posted, but in reality when you unit test, most likely you'll be doing it on your computer and therefore you won't be running into anyone else's context. (Unlike a web site)</p>
<pre>    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">String</span> MAIN_CONTEXT_KEY = <span style="color: #800000;">"MainContext"</span>;
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">TISQLEntities</span> _context;

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> RemoveContext()
    {
        <span style="color: #0000ff;">if</span> (<span style="color: #008080;">HttpContext</span>.Current != <span style="color: #0000ff;">null</span> &amp;&amp; <span style="color: #008080;">HttpContext</span>.Current.Items[MAIN_CONTEXT_KEY] != <span style="color: #0000ff;">null</span>)
        {
            ((<span style="color: #008080;">TISQLEntities</span>)HttpContext.Current.Items[MAIN_CONTEXT_KEY]).Dispose();
            HttpContext.Current.Items[MAIN_CONTEXT_KEY] = <span style="color: #0000ff;">null</span>;
        }

        <span style="color: #0000ff;">if</span>(_context != <span style="color: #0000ff;">null</span>)
        {
          _context = <span style="color: #0000ff;">null</span>;
        }
    }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">TISQLEntities</span> Context
    {
        <span style="color: #0000ff;">get</span>
        {
            <span style="color: #0000ff;">if</span> (<span style="color: #008080;">HttpContext</span>.Current == <span style="color: #0000ff;">null</span>)
            {
                <span style="color: #0000ff;">if</span>(_context == <span style="color: #0000ff;">null</span>)
                {
                    _context = <span style="color: #0000ff;">new</span> <span style="color: #008080;">TISQLEntities</span>();
                }
                <span style="color: #0000ff;">return</span> _context;
            }

            <span style="color: #0000ff;">if</span>(<span style="color: #008080;">HttpContext</span>.Current.Items[MAIN_CONTEXT_KEY] == <span style="color: #0000ff;">null</span>)
            {
                <span style="color: #008080;">HttpContext</span>.Current.Items[MAIN_CONTEXT_KEY] = <span style="color: #0000ff;">new</span> <span style="color: #008080;">TISQLEntities</span>();
            }

            <span style="color: #0000ff;">return</span> (<span style="color: #008080;">TISQLEntities</span>)<span style="color: #008080;">HttpContext</span>.Current.Items[MAIN_CONTEXT_KEY];
        }
    }</pre>
<p>I don't like this one fully, but for now it's good. There has to be a better way though.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/singleton-objectcontext-the-remix/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Querying issue follow up.</title>
		<link>http://byatool.com/lessons/entity-framework-querying-issue-follow-up/</link>
		<comments>http://byatool.com/lessons/entity-framework-querying-issue-follow-up/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 20:07:15 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=483</guid>
		<description><![CDATA[So in THIS MIGHTY POST I asked why Entity Framework context likes to query the database despite the object (data row) already being loaded into the context. Well even though it's not a perfect answer, Craig Stuntz had an answer at The O that gave some light to the situation: context.SiteUser is an property of [...]]]></description>
			<content:encoded><![CDATA[<pre>                <img title="threedoors" src="http://byatool.com/wp-content/uploads/2009/02/threedoors.png" alt="threedoors" width="337" height="230" /></pre>
<p>So in <a href="http://byatool.com/index.php/lessons/entity-framework-odd-things-during-querying" target="_blank">THIS MIGHTY POST</a> I asked why Entity Framework context likes to query the database despite the object (data row) already being loaded into the context.  Well even though it's not a perfect answer, <a href="http://blogs.teamb.com/craigstuntz" target="_blank">Craig Stuntz</a> had an answer at <a href="http://www.stackoverflow.com" target="_blank">The O</a> that gave some light to the situation:</p>
<blockquote><p>context.SiteUser is an property of type ObjectQuery. When you execute an ObjectQuery, it will always hit the backing store. That's what they do. If you don't want to execute a database query, then don't use an ObjectQuery.</p></blockquote>
<p>Furthermore I could use GetObjectByKey:</p>
<blockquote><p>GetObjectByKey tries to retrieve an object that has the specified EntityKey from the ObjectStateManager. If the object is currently not loaded into the object context, a query is executed in an attempt to return the object from the data source.</p></blockquote>
<p>Which actually seems to me like how it should work naturally. After all, if it's in the context and I am positive I don't want to update the <a href="http://byatool.com/index.php/lessons/entity-framework-concurrency-mode-and-fun-observations" target="_blank">object from changes in the database</a>, wouldn't it make sense to not bother with the database at all? Seems like a wasted action. Again, I am guessing that the reason it does this is that it's an all or nothing thing. It either does it all the time (IE query no matter the reason) or never. Grey area just doesn't seem to fit Entity Framework design in this matter.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-querying-issue-follow-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Concurrency Mode and fun observations</title>
		<link>http://byatool.com/lessons/entity-framework-concurrency-mode-and-fun-observations/</link>
		<comments>http://byatool.com/lessons/entity-framework-concurrency-mode-and-fun-observations/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 21:52:29 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=478</guid>
		<description><![CDATA[Ok so you have this thing that you want to do and it involved stuff. And when you do that stuff you want something to happen. And when that happens you want to know that it happened and tell someone, "Hey I did stuff and something happened." That, in essence, is what Concurrency Mode is [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so you have this thing that you want to do and it involved stuff. And when you do that stuff you want something to happen. And when that happens you want to know that it happened and tell someone, "Hey I did stuff and something happened." That, in essence, is what Concurrency Mode is for provided all this had to do with the Entity Framework and updating records.</p>
<p>Concurrency Mode allows you to make sure that nothing has changed in the database before or during the current save. Basically it checks the database to make sure the record being updated still is in the same condition it was when you loaded it to the context. If it isn't, then an exception is thrown. (Maybe not the way I would prefer handling this situation, but hey I don't work for the M) How do I get this to happen? Well it's a pretty easy change, though it has an annoying short coming. First the change.</p>
<p>Open up the model browser (IE double click on the .edmx file) and select any property on any entity. Then view the properties.</p>
<pre><img title="concurencymode" src="http://byatool.com/wp-content/uploads/2009/02/concurencymode.jpg" alt="concurencymode" width="372" height="238" /></pre>
<p>And in the image you can see that there is a property surprisingly named "Concurrency Mode" and there are two options: Fixed and None. Guess which one I'm talking about in this post.</p>
<p>Now if I just left you with that, you'd have everything you need to know and you wouldn't waste the next minute you're going to waste on my findings. Good thing you aren't smart enough to walk away.</p>
<p>You might wonder how the Entity Framework is able to do that, after all even I did and as we all know, I am genius.<br />
Say you have a User entity where the UserName and MainEmail properties had Fixed Concurrency. Now suppose the old values of these were 'oldValue' and you just changed them (UI Side) to 'HIHIHI'. At this point you want to save the changes. Well if you use profiler and a watch as it saves, you'll see something like this:</p>
<pre><span style="color: #0000ff;">exec</span> sp_executesql
<span style="color: #800000;">N'update [TIDBA].[TI_USER]
set
  [MainEmail] = @0,
  [UserName] = @1
where
  ((([UserID] = @2)
</span><span style="color: #800000;">and
  ([MainEmail] = @3))
and
  ([UserName] = @4))
'</span>,N<span style="color: #800000;">'@0 nchar(6),
@1 varchar(6),
@2 int,
@3 nchar(6),
@4 varchar(6)'</span>,
@0=N<span style="color: #800000;">'HIHIHI'</span>,
@1=<span style="color: #800000;">'HIHIHI'</span>,
@2=1,
@3=N<span style="color: #800000;">'oldValue'</span>,
@4=<span style="color: #800000;">'oldValue'</span></pre>
<p>Which cleans up into:</p>
<pre><span style="color: #0000ff;">update</span> [TIDBA].[TI_USER]
<span style="color: #0000ff;">set</span>
  [MainEmail] = <span style="color: #800000;">'HIHIHI'</span>,
  [UserName] = <span style="color: #800000;">'HIHIHI'</span>
<span style="color: #0000ff;">where</span>
  ((([UserID] = 1)
<span style="color: #0000ff;">and</span>
  ([MainEmail] = <span style="color: #800000;">'oldValue'</span>))
<span style="color: #0000ff;">and</span>
  ([UserName] = <span style="color: #800000;">'oldValue'</span>))</pre>
<p>As you can see, the Entity Framework matches the originally loaded values against the database (Only on Fixed Concurrency properties) and sees if it can find a record. If it can't, it means those values have changed. The exception follows.</p>
<p>Now besides the exception part (A bit much but can be handled), the only annoying thing is that you have to do this property by property. I don't see a way yet to make it standard for the entire entity. Such is life.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-concurrency-mode-and-fun-observations/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Odd things during querying</title>
		<link>http://byatool.com/lessons/entity-framework-odd-things-during-querying/</link>
		<comments>http://byatool.com/lessons/entity-framework-odd-things-during-querying/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 21:13:31 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=457</guid>
		<description><![CDATA[So in THIS POST I talked about how querying worked on a conceptual level but turns out there is something going on that's not expected. Remember how I said that if the object is in the context, the database won't be hit? Turns out that isn't true to an extent. With the help of profiler, [...]]]></description>
			<content:encoded><![CDATA[<pre><img title="serverdatabasehitit1" src="http://byatool.com/wp-content/uploads/2009/02/serverdatabasehitit1.jpg" alt="serverdatabasehitit1" width="453" height="255" /></pre>
<p>So in <a href="http://byatool.com/index.php/lessons/entity-framework-concepts-and-headaches-querying" target="new">THIS POST</a> I talked about how querying worked on a conceptual level but turns out there is something going on that's not expected.  Remember how I said that if the object is in the context, the database won't be hit?  Turns out that isn't true to an extent.  With the help of profiler, I found outconfusing thing or two, and neither have to do with why <a href="http://www.cnn.com/2009/LIVING/worklife/02/13/careereoki/index.html" target="new">this is was on the front page of CNN</a>.</p>
<p>Say you for some reason want to select a user like so:</p>
<pre>    <span style="color: #008080;">SiteUser</span> someUser = context.SiteUser.First(role =&gt; role.UserID == 1);</pre>
<p>WOW THAT IS NEW AND AMAZING!!!117!</p>
<p>Right off the bat, I bet you can guess what happens. If not (You know, if you didn't read <a href="http://byatool.com/index.php/lessons/entity-framework-concepts-and-headaches-querying" target="new">THIS POST</a> or you have difficulties with revolving doors), here's the idea in script form:</p>
<pre>            CONTEXT
    Am I having this Object?

Context looks into its bag, notices it doesn't have the object,
and then looks over at Database with confused look.

            DATABASE
   No but I gots it for you.

Database hands object to Context.  Context looks happy.

            CONTEXT
  I has a object now.</pre>
<p>At this point, two things are obvious: I've lost it and Context now has a User with an UserID of one and it got this by querying the database.   Now suppose for no real reason you want the same user. (Assume it is the same context and the user is already in the context.)</p>
<pre>            CONTEXT
    Am I having this Object?

Context looks into his bag and pulls out the object.  Database walks over.

           CONTEXT
    You has object?

            DATABASE
   Yes but I gots it for you.

Database hands object to Context.  Context doesn't take it.

            CONTEXT
  I has it already.</pre>
<p>So in this stunning display, we can see that even though the context already has the user, it still asks the database for the thing. How do I know this? Well I used profiler on both statements. What I thought would happen is on the first eh First it would hit the database, hydrate the object, and go on its merry. Second First would just grab it from the context and give it to me. Fact is, it STILL HITS THE DATABASE. Now the next possible idea is that it's going to the database to see if the record has changed and then will update the object with any changes EXCEPT what has been changed on the object. Yeah not so much. (Although there is a way you can force that, but I'll post that in the next post) Fact is, it really doesn't do anything with it as long as you have the default settings. In fact, (FACT FACT FACT FACT) the default settings say that:</p>
<pre>Objects that already exist in the object context are not loaded from the data source.
This is the default behavior for queries or when calling the Load method on an
EntityCollection&lt;(Of &lt;(TEntity&gt;)&gt;).</pre>
<p>Seems kind of odd that by default something in the context will not be loaded if it's already there but it still hits the database regardless. So what this default really means is that it may or may not hit the database, but any changes in the database will not be reflected in the object. It really doesn't mean that the database won't be queried. Seems kind of odd.</p>
<p>What not good enough?  Fine, <a href="http://www.cnn.com/2009/US/02/16/texas.sky.debris/index.html" target="_blank">figure this out.</a></p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-odd-things-during-querying/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Concepts and Headaches.  Querying</title>
		<link>http://byatool.com/lessons/entity-framework-concepts-and-headaches-querying/</link>
		<comments>http://byatool.com/lessons/entity-framework-concepts-and-headaches-querying/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 15:37:27 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=454</guid>
		<description><![CDATA[So in the first part of this life changing tutorial, I explained what lazy loading was and how it worked with the Entity Framework. Now I wanted to get into querying/loading and how it's handled. At least at a very simplistic angle. (Simplistic is what I do best. Day-oh!) Something that has to be understood [...]]]></description>
			<content:encoded><![CDATA[<p>So in the<a href="http://byatool.com/index.php/general-coding/entity-framework-concepts-and-headaches-lazy-loading" target="_blank"> first part</a> of this life changing tutorial, I explained what lazy loading was and how it worked with the Entity Framework. Now I wanted to get into querying/loading and how it's handled.  At least at a very simplistic angle.  (Simplistic is what I do best.  Day-oh!)  Something that has to be understood is how the Entity Framework handles the hydrating/loading of objects and how it relates to the ObjectContext.  Say you have the same User/Site example from the<a href="http://byatool.com/index.php/general-coding/entity-framework-concepts-and-headaches-lazy-loading" target="_blank"> first part</a> and you load a site:</p>
<pre>    <span style="color: #0000ff;">using</span>(<span style="color: #008080;">SomeEntities</span> context = new <span style="color: #008080;">SomeEntities</span> ())
    {
       <span style="color: #008000;">//where SomeEntities  : ObjectContext</span>
       <span style="color: #008080;">Site</span> neededSite = context.Site.Where(site =&gt; site.ID = siteID);
    }</pre>
<p>Ok so what happens here? Well basically the context will check itself to see if it holding said Site and if it isn't, it will grab it from the database. This doesn't seem like a big deal since it's pretty obvious it won't have the given Site yet since the context was just created. Now let's get a silly example going for the sake of learning.</p>
<pre>    <span style="color: #0000ff;">using</span>(<span style="color: #008080;">SomeEntities</span> context = <span style="color: #0000ff;">new</span> <span style="color: #008080;">SomeEntities</span> ())
    {
       <span style="color: #008000;">//where SomeEntities  : ObjectContext</span>
       <span style="color: #008080;">Site</span> neededSite = context.Site.Where(site =&gt; site.ID = siteID);
       neededSite.SiteName = someString;

       <span style="color: #0000ff;">if</span>(context.Site.Any(site =&gt; siteName == neededSite.SiteName))
       {
          <span style="color: #008000;">//return error since the name already exists in the table.</span>
       }

    }</pre>
<p>Now as it is, this doesn't seem too bad right? I change the name of the site and then see if that name is taken already in the database. If these seems ok to you it just means you don't yet understand how the Entity Framework eh... works. The first time you go to get the Site, it fills it's Site list with the Sites from the database, then checks the list for the one you want. It will then proceed to give you a reference to the Site in that list. Next time you do a query on the Sites list, it will NOT query the database but rather it will just query the Sites list it has in memory. Next, the line:</p>
<pre>    neededSite.SiteName = someString;</pre>
<p>Is updating the object in that list. Now you would think (If you are used to say not caching results from database queries) that the next query:</p>
<pre>    context.Site.Any(site =&gt; siteName == neededSite.SiteName)</pre>
<p>Would hit the database again and check the items there and make sure that SiteName doesn't exist. But far as Entity Framework is concerned it already loaded that list, so it doesn't need to hit the database again. This is good to save the performance hit of getting from the database but dangerous if you don't understand this. Fact is, the context is just going to look at it's cached list of Sites and run that query and guess what's in that list? The object that you just changed. So basically that query will compare the object to itself at some point as it iterates through the list and yee haw it will find a Site that already has that SiteName... the one you just changed. Solution?</p>
<p>You can include the SiteID in the query:</p>
<pre>    context.Sites
            .Any(
                  site =&gt; siteName == neededSite.SiteName
                  &amp;&amp; site.SiteID != neededSite.SiteID
                 )</pre>
<p>This way you know that you won't compare the same object to itself.</p>
<p>OR You can create a new context if you really want to get a fresh look at the database. This will allow you to have a context with the new changes and a context pre changes so you can be sure you are comparing the object to a list without it.</p>
<p>Now you might look down the list of methods on the context and see the Refresh method. This might be temping because you might think that a refresh would give you what you want, a completely new list to compare against. There are two ways you can handle this:</p>
<pre>     context.Refresh(<span style="color: #008080;">RefreshMode</span>.Store, context.Site);</pre>
<p>Seems like this would be good since it basically means I want to completely restore the list from the database and clear out any changes I made in the list. Oh wait, what was that? " clear out any changes I made in the list". This means those changes we made to the object, yeah gone. So now the:</p>
<pre>    context.Sites
           .Any(
                  site =&gt; siteName == neededSite.SiteName
                  &amp;&amp; site.SiteID != neededSite.SiteID
                )</pre>
<p>Query is hosed because the neededSite.SiteName has been reverted to whatever was in the database originally.</p>
<p>You could try this:</p>
<pre>     context.Refresh(<span style="color: #008080;">RefreshMode</span>.ClientWins, context.Site);</pre>
<p>In which any changes made to the objects will overwrite any information being brought in from the database. Hmm, 6 of one and a half dozen of the other. This just brings us back to the same problem. The list will still contain the changes to the object and therefore we will once again compare the object to itself.</p>
<p>Now you might think that maybe you should just check the list BEFORE applying the changes to the object, and that would be a good way of going about it:</p>
<pre>    <span style="color: #0000ff;">using</span>(<span style="color: #008080;">SomeEntities</span> context = <span style="color: #0000ff;">new</span> <span style="color: #008080;">SomeEntities</span> ())
    {
       <span style="color: #008000;">//where SomeEntities  : ObjectContext</span>
       <span style="color: #008080;">Site</span> neededSite = context.Site.Where(site =&gt; site.ID = siteID);

       <span style="color: #0000ff;">if</span>(context.Site.Any(site =&gt; siteName == someString))
       {
          <span style="color: #008000;">//return error since the name already exists in the table.</span>
       }
       <span style="color: #0000ff;">else</span>
       {
          neededSite.SiteName = someString;
          <span style="color: #008000;">//Continue or save</span>
       }
    }</pre>
<p>This would work since you are checking the list before the object has been changed. This might work if you do your saving in the same layer that you have your UI, but if you do something like this:</p>
<pre>    ...
    <span style="color: #008080;">Site</span> someSite = <span style="color: #008080;">Site</span>.GetSiteById(id);
    someSite.SiteName = txtSiteName.Text;
    someSite.Save();
    ...</pre>
<p>In this example, I have created a Save method on the Site object that will take care of validation and saving all in one. It also means that I either am sharing a context between the GetSiteId method and the Save method, or that I am using two contexts. If it's the latter, then it won't matter since the context in the Save method will not "own" the current someSite object. (And therefore will not have the changes to the someSite object reflected in its list) However, if they do share the same context then you will run into the above problem.</p>
<p>In the next post, I'll talk about how to share a context... which I won't try to sell you as the right thing to do.  Just something to think about.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-concepts-and-headaches-querying/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Concepts and headaches. Lazy Loading</title>
		<link>http://byatool.com/lessons/entity-framework-concepts-and-headaches-lazy-loading/</link>
		<comments>http://byatool.com/lessons/entity-framework-concepts-and-headaches-lazy-loading/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 14:32:35 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=447</guid>
		<description><![CDATA[So when I wrote this and this I didn't really have a precursor to some of the concepts in the posts so I figured I'd get them out of the way now since I'll be posting a bunch on the Entity Framework. First off is lazy loading. Now I could put the obligatory stupid joke [...]]]></description>
			<content:encoded><![CDATA[<p>So when I wrote <a href="http://byatool.com/index.php/lessons/entity-framework-objectcontext-observations-on-caching" target="_blank">this</a> and <a href="http://byatool.com/index.php/lessons/entity-framework-many-to-one-property-and-how-to-load" target="_blank">this</a> I didn't really have a precursor to some of the concepts in the posts so I figured I'd get them out of the way now since I'll be posting a bunch on the Entity Framework.</p>
<p>First off is lazy loading. Now I could put the obligatory stupid joke here that gives some kind of novel, but incorrect, explanation of the phrase (Like say making someone else wash your clothes) but I so much better than that. So what is lazy loading? Simply put it's not getting something until you need it. Kind of like "If it ain't broke then don't fix it" instead you trade "broke" with "needed" and "fix" with "get". So it's really not like that phrase. It is however, when talking about objects being hydrated (ie loaded) from some kind of storage (ie database) in a program written by some idiot. (ie me) Let's say you have a User table and a Site table in which there are many Users to one Site. Now with an ORM this will be represented by an User object, a Site object, and a property on User that is of type Site. It would look something like this:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">User</span>
    {
      <span style="color: #0000ff;">private</span> <span style="color: #008080;">Site</span> _site = <span style="color: #0000ff;">null</span>;

      <span style="color: #0000ff;">public</span> <span style="color: #008080;">Site</span> ParentSite
      {
         <span style="color: #0000ff;">get</span>
         {
            <span style="color: #0000ff;">if</span>(_site == <span style="color: #0000ff;">null</span>)
            {
               _site = SomeMethodToGetSite();
            }

            <span style="color: #0000ff;">return</span> _site;
         }
      }
    }</pre>
<p>When you load the User from storage, initially the Site object on the User object is null. This is done because if you don't need the Site yet, why take up space until you do? This is the concept of lazy loading. Now in most ORMs, the Site would automatically be hydrated the first time the Site property was accessed. Entity Framework is slightly more complicated when dealing with the many to many or one to many situation.</p>
<p>This happens when you have a Users list on the Site object that basically represents every User in the User table that has the same SiteID as the Site in question. OR maybe you have a hanging table UserSite that allows for one Site to have many Users and one User to have many Sites. Either way, you will be left with a collection that represents this relationship. (Users list on the Site object) Now say you do this:</p>
<pre>  <span style="color: #008080;">Site</span> someSite = LoadSiteByID(siteID);</pre>
<p>and then you try to do this:</p>
<pre>  someGrid.DataSource = someSite.Users;
  someGrid.DataBind();</pre>
<p>When the page loads, there are no records in the grid. In a normal ORM this wouldn't be a problem. It would see that you are accessing the .Users property and hit the database to fill the list. Entity Framework requires you to take one more step in this case.</p>
<pre>  someGrid.DataSource = someSite.Users.Load();</pre>
<p>Not that big of a deal. Now there is a check even to see if it is loaded in the first place:</p>
<pre>  order.Users.IsLoaded</pre>
<p>This is a boolean property that says true when it has been loaded. Next post I'll hit on what happens when you query and how that relates to this situation.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-concepts-and-headaches-lazy-loading/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: ObjectContext observations on caching</title>
		<link>http://byatool.com/lessons/entity-framework-objectcontext-observations-on-caching/</link>
		<comments>http://byatool.com/lessons/entity-framework-objectcontext-observations-on-caching/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 15:53:33 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=433</guid>
		<description><![CDATA[I thought that my journey with the Entity Framework was going to be like falling off a cliff, fast and painless but instead it's been more like driving a Hummer in a Smart car convention, just have to plow my way through. The latest bump in my path has been the ObjectContext. Just to let [...]]]></description>
			<content:encoded><![CDATA[<p>I thought that my journey with the Entity Framework was going to be like falling off a cliff, fast and painless but instead it's been more like driving a Hummer in a Smart car convention, just have to plow my way through.</p>
<p>The latest bump in my path has been the ObjectContext.  Just to let it be known, I'm like most kids with a new game, I don't bother to read the instructions and the throw the controller when I don't have a clue what I'm doing.  My use of the Entity Framework has been no different.  So using "o' skool" standards, I immediately decided that I would have some kind of Singleton context so that I didn't keep making new ones, and assumedly new connections.  Everything seemed fine and dandy until <a title="http://byatool.com/index.php/uncategorized/entity-framework-many-to-one-property-and-how-to-load" href="http://" target="_blank">I hit this</a> situation which brought some, at the time, unexplainable or difficult issues.</p>
<p>First off, say you have a Site and Role class, and Role is Many to One with Site.  Now let's say you are creating a page that is used to create/update/delete roles.  On this page you have the usual section for updating or creating a new role that involves a Name for the Role and a drop down list to pick a Site from.  Now on the update side of it you have basic rules:  The Role must have a name, the Role must have a Site, and the Name of the Role can't already exist in the database for the site.  So a new role might look like:</p>
<pre>  <span style="color: #008080;">Role</span> editRole = Role.GetByID(someID);
  editRole.RoleName = txtRoleName.Text;
  editRole.Site = GetSiteFromID(ddlSite.SelectedValue.ConvertTo&lt;<span style="color: #008080;">Int32</span>&gt;);</pre>
<p>The GetByID is just a query that gets the Role by and ID by using the Singleton ObjectContext. (KEY POINT) Beyond that, nothing special except my <a title="http://byatool.com/index.php/utilities/duck-typing-my-way-to-a-universal-string-convert" href="http://" target="_blank">awesome string convert. Yah.</a> Now the next step before committing to the database is something like:</p>
<pre>  <span style="color: #0000ff;">if</span>
  (
    context.Any
    (
      role =&gt; role.Name == editRole.RoleName
      &amp;&amp; role.Site == editRole.Site
    )
  )
  {
     <span style="color: #008000;">//return error or whatever</span>
  }</pre>
<p>So right there I'm checking to see if the new name for the role exists already. Now say I'm updating a role and that I KNOW the new name doesn't exist. You would think that query would return false and life would be good. Unfortunately two things happened... and they will change your life forever.  (EDIT:  I realize I could also check to make sure the ID doesn't match and should do that, but if I had done that initially I wouldn't have figured out the next part)</p>
<p>First:</p>
<p>I got back an error saying the name already exists. Now as I said, I know it didn't so how could that happen? Well remember that Singleton ObjectContext idea? First time I grab the Role, it doesn't exist in the ObjectContext.Role list. So it grabs it from the database and then stores it so that every time I now run that GetByID method, I am actually getting the object from the context NOT THE PERSISTENCE LAYER. (IE database or whatever) Therefore, any changes I make are changes to the object in that context. So what does that mean? Well say I do update the RoleName on that object and then run a query to see if that name exists, guess where that query is looking? Yup the context. And since it's looking at the same stupid object I just changed, of course the name is going to exist now. Basically I comparing the object to itself to see if it's name exists. Ouch.</p>
<p>B:</p>
<p>After cancelling, (IE not saving) The grid that I had displaying all the Roles now has that new RoleName in it. What the f? My code specifically says NOT to save unless that (name already exists) query returns false. So how the hell has the name changed? Well just like before, the query that gets the list of Roles is no longer looking at the database but now at the Roles list in the context. That same Roles list that has the Role I changed earlier. Therefore any change to that object will now be reflected when getting the list from the context. Uhg.</p>
<p>So what can you learn about this? Once a list is "loaded" for the first time, it is held in the context until (presumably) you use the Refresh method on the context to refresh the given list. (Not sure how well this works). Therefore, any queries after the first will reflect all changes to the objects in the context, whether you saved to the database or not. The Singleton idea isn't looking real great right now.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-objectcontext-observations-on-caching/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Many to One property and how to load</title>
		<link>http://byatool.com/lessons/entity-framework-many-to-one-property-and-how-to-load/</link>
		<comments>http://byatool.com/lessons/entity-framework-many-to-one-property-and-how-to-load/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 17:54:03 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=430</guid>
		<description><![CDATA[Ok so this is the situation, you've just stolen 50 billion dollars from various wealthy people using a ponzi scheme and you've been caught. What do you do? I have no idea but if that's your situation and you've ended up at this site, I'm guessing your escape route has something to do with the [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so this is the situation, you've just stolen 50 billion dollars from various wealthy people using a ponzi scheme and you've been caught.  What do you do?   I have no idea but if that's your situation and you've ended up at this site, I'm guessing your escape route has something to do with the Entity Framework and how to load a many to one relationship.  Or maybe you're just interested in the latter anyhow. </p>
<p>So here's the problem I ran into the other day.  I have a Site table and a Role table, and every Role record has a SiteID (Foreign Key) that the Entity Map represents in a property.  (Site Class)  Now, when I "hydrate" a Role, the Site property is null.  This is because Entity Framework, in a round about way, supports lazy loading sort of.  (Lazy Loading meaning that any relationship, be it a Site object on a Role or say a Users list on a Role, will not be loaded at the time you "hydrate" the main object and will only be loaded when the property is accessed.)  So it makes sense that the Site object exposed by the property is not loaded yet because I haven't accessed the property. </p>
<p>With the Entity Framework, and one to many relationships (Say a Users list on a Role object) you have to not only access the property, but you have use the Load method to make sure it gets loaded:</p>
<pre>    <span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> someRole.Users.Load()</pre>
<p>Well with a many to one relationship (Many Roles to one Site) this is a propblem since the Site property returns only a single Site:</p>
<pre>    someRole.Site.Load(); <span style="color: #008000;">//Boom, not possible</span></pre>
<p>Load can't be used since Site isn't a collection. So how the hell do I load this stupid thing? Well that has to be done in the query itself. Kind of annoying:</p>
<pre>    context.Role.Include(<span style="color: #800000;">"Site"</span>).Where(someClause).ToList();</pre>
<p>As you can see, in that query I had to add the Include method and the value is actually the property name. Now when I look at the list of roles returned, the roles now have the Site property loaded. As I said, kind of annoying, but there is something interesting about these relationships that I'll post about next.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li><li><a href="http://byatool.com/pontification/entity-framework-am-i-just-being-stubborn/" title="Entity Framework:  Am I Just Being Stubborn?">Entity Framework:  Am I Just Being Stubborn?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/entity-framework-many-to-one-property-and-how-to-load/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
