<?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>Shawson&#039;s Code Blog &#187; Linq</title>
	<atom:link href="http://codeblog.shawson.co.uk/category/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://codeblog.shawson.co.uk</link>
	<description>development notes for my failing memory</description>
	<lastBuildDate>Tue, 15 May 2012 15:22:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</title>
		<link>http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/</link>
		<comments>http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 20:43:50 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1091</guid>
		<description><![CDATA[A quick piece of code demo&#8217;ing a very common/ simple usage scenario- basic one to many with some demo data being seeded into the database; I thought this might be needed as I&#8217;ve waded through a LOT of exmaples for various beta versions and different releases of EF, but had little luck actually finding something [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/linq-distinct/' rel='bookmark' title='Linq Distinct!'>Linq Distinct!</a></li>
<li><a href='http://codeblog.shawson.co.uk/syndicating-to-rss-using-the-build-in-net-syndicationfeed-classes/' rel='bookmark' title='Syndicating to RSS using the built in .net SyndicationFeed classes'>Syndicating to RSS using the built in .net SyndicationFeed classes</a></li>
<li><a href='http://codeblog.shawson.co.uk/creating-an-order-order-details-style-form-using-asp-net-mvc2-entity-framework/' rel='bookmark' title='Creating an Order/ Order Details style view using ASP.net MVC2 &amp; Entity Framework 4'>Creating an Order/ Order Details style view using ASP.net MVC2 &#038; Entity Framework 4</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>A quick piece of code demo&#8217;ing a very common/ simple usage scenario- basic one to many with some demo data being seeded into the database; I thought this might be needed as I&#8217;ve waded through a LOT of exmaples for various beta versions and different releases of EF, but had little luck actually finding something relevant.  The best site I came across was tucked away on the ADO.net team&#8217;s blog- <a href="http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-1-introduction-and-model.aspx">Using DbContext in EF 4.1</a>.  First&#8211; the entities and the database context</p>
<pre class="brush: csharp">
    public class Category
    {
        [Key]
        public Guid ID { get; set; }

        public string Title { get; set; }
        public virtual ICollection&lt;Product&gt; Products { get; set; }
                   //virtual makes this lazily loaded

        public Category()
        {
            this.ID = Guid.NewGuid();
        }
    }

    public class Product
    {
        [Key]
        public Guid ID { get; set; }

        public string Title { get; set; }
        public string Details { get; set; }
        public double Price { get; set; }
        public string ImageFileName { get; set; }

        public DateTime DateAdded { get; set; }

        public virtual Category Category { get; set; }
                   //virtual makes this lazily loaded

        public Product()
        {
            this.ID = Guid.NewGuid();
        }
    }

    public class MyDBContext: DbContext
    {
        public DbSet&lt;Product&gt; Products { get; set; }
        public DbSet&lt;Category&gt; Categories { get; set; }
    }
</pre>
<p>Note the use of ICollection on Products in Category, and the use of DbSet in the context.  I used a DbSet in lieu of ICollection on the Products entity and found it went mental if I had a Product with no category (something which I wanted to be valid) &#8211; swapping it to ICollection fixed this issue (I don&#8217;t know enough of the inner workings to explain why) </p>
<p>BAMM!  Next for the seeding- add a class like so;</p>
<pre class="brush: csharp">
    public class MyDBInitializer : DropCreateDatabaseAlways&lt;MyDBContext&gt;
    {
        protected override void Seed(Entities.ComicolleDB context)
        {
            Category marvel = new Category()
            {
                Title = &quot;Category 1&quot;
            };
            Category dc = new Category()
            {
                Title = &quot;Category 2&quot;
            };

            context.Categories.Add(marvel);
            context.Categories.Add(dc);

            context.Products.Add(new Product()
            {
                Title = &quot;Test1&quot;,
                ImageFileName = &quot;image-1.gif&quot;,
                Details = &quot;This is a test&quot;,
                Price = 4.99,
                DateAdded = DateTime.Now,
                Category = marvel
            });

            context.Products.Add(new Product()
            {
                Title = &quot;Test2&quot;,
                ImageFileName = &quot;image-1.gif&quot;,
                Details = &quot;This is a test&quot;,
                Price = 4.99,
                DateAdded = DateTime.Now,
                Category = dc
            });

            context.Products.Add(new Product()  // no category
            {
                Title = &quot;Test3&quot;,
                ImageFileName = &quot;image-1.gif&quot;,
                Details = &quot;This is a test&quot;,
                Price = 4.99,
                DateAdded = DateTime.Now
            });

            context.SaveChanges();
        }
    }
</pre>
<p>Then add the following line to the end of your Application_Start() method in global.asax;</p>
<pre class="brush: csharp">
Database.SetInitializer&lt;MyDBContext&gt;(new MyDBInitializer());
</pre>
<p>Voila- you can then go ahead and use your model in whatever applications you see fit- here are some example;</p>
<pre class="brush: csharp">
MyDBContext db = new MyDBContext();

// get a category, and make sure the products are loaded
Category the_category = db.Categories.Include(&quot;Products&quot;)
                           .Where(x =&gt; x.Title == &quot;Category 1&quot;).SingleOrDefault();

// get all the products for that category
List&lt;Product&gt; some_products = the_category.Products;

// get all the categories (without loading the products)
List&lt;Category&gt; some_categories = db.Categories.ToList();
</pre>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/linq-distinct/' rel='bookmark' title='Linq Distinct!'>Linq Distinct!</a></li>
<li><a href='http://codeblog.shawson.co.uk/syndicating-to-rss-using-the-build-in-net-syndicationfeed-classes/' rel='bookmark' title='Syndicating to RSS using the built in .net SyndicationFeed classes'>Syndicating to RSS using the built in .net SyndicationFeed classes</a></li>
<li><a href='http://codeblog.shawson.co.uk/creating-an-order-order-details-style-form-using-asp-net-mvc2-entity-framework/' rel='bookmark' title='Creating an Order/ Order Details style view using ASP.net MVC2 &amp; Entity Framework 4'>Creating an Order/ Order Details style view using ASP.net MVC2 &#038; Entity Framework 4</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Entity Framework &#8220;The data reader is incompatible with the specified complex type.&#8221;</title>
		<link>http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/</link>
		<comments>http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/#comments</comments>
		<pubDate>Tue, 07 Jun 2011 16:07:21 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#.net]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://codeblog.shawson.co.uk/?p=1024</guid>
		<description><![CDATA[I recently had this problem with a site I&#8217;m working on. I&#8217;m using Entity framework to access a bunch of legacy stored procedures, originally in MySQL but ported over to MSSQL. Having added the sprocs to EF and let it auto-generate it&#8217;s magic, I was shocked to find one of my calls throwing the following [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/cross-apply-in-sql/' rel='bookmark' title='Cross Apply in SQL'>Cross Apply in SQL</a></li>
<li><a href='http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/' rel='bookmark' title='Entity Framework 4.1 Code First (With One to Many relationship) Code Example'>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</a></li>
<li><a href='http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/' rel='bookmark' title='Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor'>Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I recently had this problem with a site I&#8217;m working on.  I&#8217;m using Entity framework to access a bunch of legacy stored procedures, originally in MySQL but ported over to MSSQL.  Having added the sprocs to EF and let it auto-generate it&#8217;s magic, I was shocked to find one of my calls throwing the following exception;</p>
<pre>
System.Data.EntityCommandExecutionException: The data reader is incompatible with the specified &amp;#39;ChinookModel.GetVehicleDescFromModelId_Result1&amp;#39;. A member of the type, &amp;#39;ivaluationid1&amp;#39;, does not have a corresponding column in the data reader with the same name.
   at System.Data.Query.InternalTrees.ColumnMapFactory.GetMemberOrdinalFromReader(DbDataReader storeDataReader, EdmMember member, EdmType currentType, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.GetColumnMapsForType(DbDataReader storeDataReader, EdmType edmType, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndType(DbDataReader storeDataReader, EdmType edmType, EntitySet entitySet, Dictionary`2 renameList)
   at System.Data.Query.InternalTrees.ColumnMapFactory.CreateFunctionImportStructuralTypeColumnMap(DbDataReader storeDataReader, FunctionImportMapping mapping, EntitySet entitySet, StructuralType baseStructuralType)
   at System.Data.EntityClient.EntityCommandDefinition.FunctionColumnMapGenerator.System.Data.EntityClient.EntityCommandDefinition.IColumnMapGenerator.CreateColumnMap(DbDataReader reader)
   at System.Data.Objects.ObjectContext.CreateFunctionObjectResult[TElement](EntityCommand entityCommand, EntitySet entitySet, EdmType edmType, MergeOption mergeOption)
   at System.Data.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, MergeOption mergeOption, ObjectParameter[] parameters)
   at System.Data.Objects.ObjectContext.ExecuteFunction[TElement](String functionName, ObjectParameter[] parameters)
   at Chinook.Model.ChinookEntities.GetVehicleDescFromModelId(Nullable`1 modelid) in C:\_Dev\Chinook\Source\Chinook.Model\Chinook.Designer.cs:line 160
   at Chinook.Model.GlassGuideDataProvider.GetVehicleFromModelId(Int32 ModelId) in C:\_Dev\Chinook\Source\Chinook.Model\GlassGuideDataProvider.cs:line 104
   at Chinook.Services.VehicleDataLookup.GetVehicleForRegistration(String reg) in C:\_Dev\Chinook\Source\Chinook\Services\VehicleDataLookup.asmx.cs:line 81
</pre>
<p>It seemed to be moaning that one of the columns in the complex type I set for it to use as the return type, doesn&#8217;t match to a column actually being returned, despite entity framework having auto generated that type itself!  The cause was, as is generally the case,  user error.  Inspecting the sproc a bit closer I noticed one of the columns was being returned twice, using the same name.  EF generated me a call with an iValuation and iValuation1 column, but failed to match iValuation1 because in reality both columns were simply called iValuation!  So a simple, and kind of obvious fix, but worth noting to stop someone else loose a little more hair when they&#8217;re confonted with this error!</p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/cross-apply-in-sql/' rel='bookmark' title='Cross Apply in SQL'>Cross Apply in SQL</a></li>
<li><a href='http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/' rel='bookmark' title='Entity Framework 4.1 Code First (With One to Many relationship) Code Example'>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</a></li>
<li><a href='http://codeblog.shawson.co.uk/asp-net-build-step-to-minify-and-obfuscate-your-sites-javascript-and-css/' rel='bookmark' title='Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor'>Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/entity-framework-the-data-reader-is-incompatible-with-the-specified-complex-type/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linq Distinct!</title>
		<link>http://codeblog.shawson.co.uk/linq-distinct/</link>
		<comments>http://codeblog.shawson.co.uk/linq-distinct/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 14:07:40 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.shawson.co.uk/codeblog/?p=366</guid>
		<description><![CDATA[I have a List of books- each book has a category &#8211; i want to find out all the unique categories involved, given a list of books- i knew i could do this with linq, but not quite sure how! It turned out to be easy.. List&#60;Category&#62; categories = _books.Select(i =&#62; i.Category).Distinct(); There was a [...]


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/' rel='bookmark' title='Entity Framework 4.1 Code First (With One to Many relationship) Code Example'>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</a></li>
<li><a href='http://codeblog.shawson.co.uk/syndicating-to-rss-using-the-build-in-net-syndicationfeed-classes/' rel='bookmark' title='Syndicating to RSS using the built in .net SyndicationFeed classes'>Syndicating to RSS using the built in .net SyndicationFeed classes</a></li>
<li><a href='http://codeblog.shawson.co.uk/reading-writing-xml-files-with-linq/' rel='bookmark' title='Reading &amp; Writing XML Files with LINQ'>Reading &#038; Writing XML Files with LINQ</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>I have a List of books- each book has a category &#8211; i want to find out all the unique categories involved, given a list of books- i knew i could do this with linq, but not quite sure how!</p>
<p>It turned out to be easy..</p>
<pre class="brush: csharp">
List&lt;Category&gt; categories = _books.Select(i =&gt; i.Category).Distinct();
</pre>
<p>There was a minor complication however- Distinct obviously needs to be able to compare different instances of Category- you can supply a delegate to a custom EquityComparer class- otherwise it will simply check if this is the same instance of the object, which will (probably) always come back false rendering your distinct useless.  So i created this;</p>
<pre class="brush: csharp">
    public class CategoryComparer : IEqualityComparer&lt;Category&gt;
    {
        public bool Equals(Category x, Category y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Category obj)
        {
            return obj.Id.GetHashCode();
        }
    }
</pre>
<p>then updated my linq to use it..</p>
<pre class="brush: csharp">
List&lt;Category&gt; categories = _books.Select(i =&gt; i.Category).Distinct(new CategoryComparer());
</pre>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/' rel='bookmark' title='Entity Framework 4.1 Code First (With One to Many relationship) Code Example'>Entity Framework 4.1 Code First (With One to Many relationship) Code Example</a></li>
<li><a href='http://codeblog.shawson.co.uk/syndicating-to-rss-using-the-build-in-net-syndicationfeed-classes/' rel='bookmark' title='Syndicating to RSS using the built in .net SyndicationFeed classes'>Syndicating to RSS using the built in .net SyndicationFeed classes</a></li>
<li><a href='http://codeblog.shawson.co.uk/reading-writing-xml-files-with-linq/' rel='bookmark' title='Reading &amp; Writing XML Files with LINQ'>Reading &#038; Writing XML Files with LINQ</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/linq-distinct/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reading &amp; Writing XML Files with LINQ</title>
		<link>http://codeblog.shawson.co.uk/reading-writing-xml-files-with-linq/</link>
		<comments>http://codeblog.shawson.co.uk/reading-writing-xml-files-with-linq/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 08:07:27 +0000</pubDate>
		<dc:creator>shawson</dc:creator>
				<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.shawson.co.uk/codeblog/?p=341</guid>
		<description><![CDATA[LINQ to XML Quick Brain Dump &#8211; Garry Pilkington. Related posts:Linq Distinct!


Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/linq-distinct/' rel='bookmark' title='Linq Distinct!'>Linq Distinct!</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p><a href="http://weblogs.asp.net/garrypilkington/archive/2009/08/25/linq-to-xml-quick-brain-dump.aspx">LINQ to XML Quick Brain Dump &#8211; Garry Pilkington</a>.</p>


<p>Related posts:<ul><li><a href='http://codeblog.shawson.co.uk/linq-distinct/' rel='bookmark' title='Linq Distinct!'>Linq Distinct!</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://codeblog.shawson.co.uk/reading-writing-xml-files-with-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

