Zeeshan Hirani
-
Ordering Lazy Loaded Child Collections on the database
I have been working with OR mappers for more than 3 years and had the luxury to work with many different ones such as Wilson, NHibernate, Sonic and Linq. One of the constraints that I have encountered in most ormappers is, there is no clean way to define how to sort child collections based on certain column. For example if I have a customer instance in my hand and I want to get access to its Orders, I can simply navigate to Orders property of the customer. What if I want those orders to be sorted by ShipCity. Well in Linq queries you can apply OrderBy operator on Orders collection for the customer. But does that order by operation gets executed on SQL server. The answer is no. As soon as we access the Orders property of the customer, Linq to SQL fetches all the orders for the customer in memory. From there on any operations you perform will get executed in memory. Below is an example that confirms the behavior.
-
Returning Random Products Using Linq To SQL
Today at work, I was given a requirement to randomize our featured products on the home page. Basically every time you reload the page, you get different set of products. The maximum number of random products you could display on home page must not be more than 20. I could have done the implementation in C# by bringing more products than I need and randomly picking up 20 from the list. Once I implemented the solution, my results were truly not randomized. I ended up with same records quite often because the randomizer function did not have enough products to randomize and plus I was bringing more data than I needed. Meaning to randomly pick 20 products, I had to bring 100 products and apply random function on there. After having done that I realized that if I were to do the randomizing on SQL server I truly would get a random behavior. SQL server has a function called NewID that always give you a random generated number. So if I can order my collection by the random generated Id, my top 20 collection of products would always give me random 20 products from products table. Here is the view and a function that returns a random Id.
-
Building Expression Trees from Scratch
Just out of curiosity i decided to create expression trees from scratch instead of using lambda statements to get my expressions trees. In all my projects, I haven't really found any significant need to create expression trees from scratch. Most of the time lambda statements are sufficient for me to create any complex expressions. However to understand lambda expressions better, it think it is essential to comprehend, how compiler converts lambda statements to expression syntax. In the example below, I am going to create a very simple expression tree that takes two parameters, multiples both parameters and adds two it.
-
Different ways of removing elements from XML
Linq to XML provides numerous ways of modifying XML which includes adding, updating and deleting nodes. I happen to work on an XML document from which I had to remove some xelments. Surprisingly I found numerous options that facilitate deleting of various xelements from XML loaded in memory. Depending on where you are in the XML tree, you might find one method easier than the other. Here is a simple example that illustrates various ways I discovered of removing xelements from XML loaded in memory.
-
XElement.ToString returns encoded text
I am sure people who do XML on a day to day basis would not find surprising but I think it was pretty cool to see that when I call ToString on my XML, I get back my entire XML with whitespace preserved and also all text is encoded for me automatically. I created my XML using .net 2.0 api and saw the same behavior so I guess this was not a new feature but definitely a good default option to encode your text before outputting it to the user. Here is simple example that illustrates this behavior.
-
Avoid impurities in Linq To SQL
This problem actually troubled me for hours until I accidentally figured out how to get around it. What I learned is try to avoid impurities in Linq statements. For instance, if you lambda expression's filter is applied by indexing an array value, do not access the array directly inside the lambda value. Instead get the value from the array assign it to a variable and use the variable in the Linq to SQL filter statements. I am not sure why I have to declare a variable to avoid an impurity. But if you do not follow this technique, more than likely you would end up with runtime error in your Linq statement. Even if you get pass the runtime error, you would end up with a wrong filter value being applied on your lambda expressions. Let's take a look at an example to understand the problem I am trying to describe.
-
Applying aggregates to empty collections causes exception in Linq To SQL
I spent nearly two hours trying to figure out what was wrong with my Linq to SQL query. Basically I was trying to calculate the sum of sales generated by each sales agent. In order to accomplish that I had to travel from employee table to Orders which had the employeeid linked to it. From the Order table I navigated to its order details and calculated the sum of Quantity ordered multiplied by Unit Price. The query works fine when each agent has put in an order in the database. But when there is no order record for an agent the sum operation performed on SQL server returns null. When Linq to SQL tries to assign null values to data types that is not defined as null, it throws an exception. Below is an example that demonstrates this issue.
-
Entity Refs Not getting serialized with WCF service
In one of the project that I am working on, my client requires me to use WCF service to talk to Linq To SQL datacontext. The infrastructure guys would not open up port for me to access SQL server directly. Therefore I created a WCF project in my solution, added a reference to Business library and exposed my Linq to SQL entities using WCF service. By default you cannot expose your Linq to SQL entities, you have to mark SerializationMode on the datacontext to Unidirectional. Once you configure the datacontext for wcf serialization, the generated entities are marked with DataContract attribute and properties on the entity are marked with Datamember attribute. If Linq to SQL entity have child entities those also get serialized. However child entities do not get lazy loaded, you have to explicitly call LoadWith to immediately load child collections for them to be serialized. Here is a simply example that illustrates the behavior.
-
Automatic entityset mapping in Entity Framework
As I am starting to do work on both linq to SQL and linq to entities, I am finding lots of subtle differences on both implementations. Some implementations I would consider as being better over the other.
-
Eager Loading child entities in Entity Framework
Once again I am comparing different behaviors in linq to SQL and entity framework. If you want to eagerly load child entities in Linq to SQL, you would use LoadWith operator available on DataLoadOptions. LoadWith method retrieves related objects for the main object. You have the option to call LoadWith method as many times as you need depending upon how many related objects you want to eagerly load. If you want to eagerly load related objects in entity framework, you you can call include method. Include takes a path which represents the name of the related entity that you want to load. In the path parameter you can also use traversal by using dot notations. For instance for a particular customer, if you want to load its Orders and for each order want to load its OrderDetails, instead of making of two Include calls you can call include with a traversal like cust.Include("Orders.OrderDetails"). This tells entity framework to load Orders and for each Order load its OrderDetails as well. As with linq to SQL, you also can make more than 1 calls to Include to load multiple entities at the same time. Below is an example that illustrates different usage of eager loading with entity framework and linq to SQL.