MICHELVANDERVLUGT.NET RSS 2.0
 Wednesday, May 21, 2008

This week I ran into a quite unexpected exception that was thrown when I tried to remove an object from my LINQ ToSQL DataContext:

System.InvalidOperationException: An attempt was made to remove a relationship between a Master and a Detail. However, one of the relationship's foreign keys (Detail.MasterId) cannot be set to null..

The example in which this occurred isn't very exotic, just a Master table and a Detail table and a relationship with a foreign key MasterId in the Detail table (which doesn't allow null's). So it should be perfectly valid to remove a row from the Detail table and submit the changes.

 

Unfortunately there is a problem with this in LINQ To SQL, which is best explained by this post of Beth Massi. She states that to work around this problem you have to manually alter the dbml using an XML editor and add DeleteOnNull="true" to the association. And yes, this solves the problem. 

 

Beth discovered this problem in VS2008 Beta 2 and it still exists in the final release. Let's hope the problem is solved with the upcoming SP1...

Wednesday, May 21, 2008 8:06:22 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [1] -

 Monday, April 07, 2008

LINQ uses a Deferred Execution model which means that nothing really happens until the results of the query are accessed, e.g. in a for(each)-loop. One of the advantages of this model is that you can compose complex queries in multiple steps to make them more readable. So from a execution point of view I expected that it should not matter whether you create the query in one complex statement, or in multiple smaller statements. But unfortunately that's not always the case...

To see the difference I've created an XML document and two simple queries that create Album objects when the where-clause matches.

The 'complex' query:

   1:  var query1 = from a in albums.Descendants("Album")
   2:               where a.Element("Artist").Value == "Radiohead"
   3:               select new Album
   4:               {
   5:                   Artist = a.Element("Artist").Value,
   6:                   Title = a.Element("Title").Value
   7:               };

The decomposed, more readable query:

   1:  var query2 = from a in albums.Descendants("Album")
   2:               select new Album
   3:               {
   4:                   Artist = a.Element("Artist").Value,
   5:                   Title = a.Element("Title").Value
   6:               };
   7:   
   8:  query2 = from a in query2
   9:           where a.Artist == "Radiohead"
  10:           select a;

The result from both queries is exactly the same, but they execute differently. What happens in Query2 is that first a list of all Album objects is created and then the ‘where’ part is evaluated over each object. This is different compared to Query1 in which an Album object is only created when it matches the ‘where’ part. So in this example Query1 is more efficient.

Is this what we should expect of deferred execution with LINQ? Yes, at least on implementations based on IEnumerable<T>. What basically happens is that a chain of methods is created and executed in the same order as added to the query. This makes Query1: albums.Where(...).Select(...) and Query2: albums.Select(...).Where(...).

With implementations based on IQueryable<T>, like LINQ To SQL, this is different in a way that it uses an Expression Tree to analyze/optimize the query. Using the same two queries with LINQ To SQL both queries execute exactly the same! Only one SQL statement is send to database and they both include the where-clause, which make them equally efficient.

In this example it isn't that much a problem but when more data is involved this is definitely something to be aware of when composing LINQ queries.

Monday, April 07, 2008 6:21:43 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -
 | 
 Saturday, October 06, 2007

With the release of Visual Studio 2008 a great new feature will be added: access to the source code of the .NET Framework libraries! In this post of Scott Guthrie he announces that VS2008 will support downloading the source code from the Internet so you are able to debug the .NET Framework libraries.

This is really a great thing because now we get more insight in how the .NET Framework is implemented and why some things might not work as expected. Up until now there is the possibility to use Reflector to explore the framework libraries, but this will be much easier as it supports the debug ability...

Saturday, October 06, 2007 11:16:45 AM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -

 Wednesday, August 15, 2007

In this post I will wrap up some of the smaller but very useful new features of .NET 3.5/C# 3.0. Other features of .NET 3.5 I've already covered are Extension Methods and Lambda Expressions.

Object and Collection Initializers
This feature makes it easier to create objects and assign values to the properties of the objects. Until .NET 3.5 you either had to write code that created an object and initialized each property of the object, or use a constructor that takes a list of parameters (which had to change of be overloaded when a property was added). The same is true for creating lists of object, calling the Add method for every new object. The following example shows that object and collection initializers makes this easier, without the use of parameter constructors:

persons = new List<Person> { new Person { Name = "Person I" }, new Person { Name = "Person II" }, new Person { Name = "Person III" }, new Person { Name = "Person IV" } };

In the example above the default constructor (without parameters) of Person will be used, witch will be executed before the property initialization. In case an alternative constructor is required, e.g. including a read only Id, the following syntax can be used:

Person person = new Person("NewGuid") { Name = "Person" };

Automatic Property get/set
The feature of automatic property takes away the burden of explicitly coding a private field and the get/set of a property, these are generated automatically by the compiler. The syntax is similar to the way of defining an abstract property or a property in an interface:

public class Person { public string Name { get; set; } }

If necessary the get/set can be changed to limit accessibility, e.g. Name { get; private set; }. Of course the object initializers as explained above cannot be used outside the class anymore.

Implicitly Typed Local Variables and Arrays
With implicitly typed variables the type of the variable is not defined up front but inferred by the compiler using the initialization of the variable. Basically this looks the same as defining the variable as an object, but there is a huge difference: after initialization the type is fixed and cannot be changed, e.g. by assigning a value of another type.

var a = 5; // int var b = 5.5; // double var c = a + b; // double var d = new int[] { 1, 2 }; // int array var e = new[] { 1, 2 }; // implicitly typed int array foreach (var f in e) Console.WriteLine(f);

Using the var keyword is only allowed for local variables, they cannot be used as class variables for example. Also, they have to be initialized when they are declared.

The usage of implicitly typed variables as aboveis a bit doubtful I think, in fact it does make the code less readable (although IntelliSense can help you out). In relation to LINQ and Anonymous Types it does make more sense though, but more on that later.

Anonymous Types
Anonymous Types are objects that are defined and created on the fly using object initializers. The compiler actually creates properties of the initializers which can be used later on. The name of the type remains unknown and cannot be used within the program.

var p1 = new { Name = "Person I", City = "New York" }; Console.WriteLine( string.Format("{0} from {1}", p1.Name, p1.City));

Like implicitly Typed Variables the usage of Anonymous Types in this context doesn't seem to be very useful because you really cannot do much with such an object. With LINQ the usage will be more frequent, e.g. to display a selection from an executed query:

var nyPersons = from q in persons where q.Address.City == "New York" select new { Name = q.Name, City = q.Address.City }; foreach (var nyp in nyPersons) Console.WriteLine(string.Format("{0} from {1}", nyp.Name, nyp.City));

The source code of these examples can be downloaded from here: TypesVariablesAndInitDemo.zip (,95 KB)

Wednesday, August 15, 2007 8:58:16 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -

 Thursday, August 09, 2007

In addition to my first post about the new .NET 3.5 language features my second post in this series will be about Lambda Expressions. Lambda Expressions are basically a follow up to Anonymous Methods (in-line delegates), which were introduced in .NET 2.0. The advantage of Lambda Expressions over anonymous methods is that it is a superset of anonymous methods (more functionality) and that it provides a more concise, functional syntax for writing Anonymous Methods (C# 3.0 specification).

Based on the example of my Extension Methods post a foreach method, which takes a generic Action delegate as a parameter, can be created with an anonymous method. To invoke the SaySomething method for every Person object in the list you can write:

_persons.ForEach(delegate(Person p) { p.SaySomething("Hello"); } );

Using the Lambda Expression syntax this same code will be:

_persons.ForEach( p => p.SaySomething("Hello") );

The syntax of param => expression is not only shorter and easier to read (once you are used to it), it is also implicitly typed. The type of p is inferred by the compiler and IntelliSense as a Person object, which is possible because the ForEach method is executed on a list of Person objects. The parameter p can also be explicitly typed by using the syntax (Person p) => p.Say...().

In this case, where the Lambda Expression takes one parameter and doesn't have a return value, the definition of the method is with a parameter of the generic delegate type Action<T>. So in case you want to write a method, e.g. as an IList extension, that takes these kind of Lambda Expressions you can write:

public static void MyForEach<T>(this IList<T> list, Action<T> doFunc)

This method can be invoked exactly the same as the normal ForEach method, with either a delegate or a Lambda Expression. Of course a lot of other great constructions are possible, for example a DoIfMatch method that executes an action when there is a match found. Note that for the match function you use the generic delegate Func<T, R>, where T is the type of the input parameter and R is the type of the result:

public static void DoIfMatch<T>(this IList<T> list, Func<T, bool> matchFunc, Action<T> doFunc)

This method can be called using:

_persons.DoIfMatch( p => p.Name == "Person II", p => p.SaySomething("Hello") );

In relation to LINQ Lambda Expressions are used in the Where-part and the OrderBy-part. There is a distinction however in LINQ implementations based on IEnumerable and IQueryable. The first one uses the Func<T, R> delegates as explained above. The latter one however uses the Expression<Func<T, R>>, which makes evaluation of the Lambda Expression possible. This way LINQ to SQL, for example, can add the where part in de SQL query before it is send to the database. The Lambda Expression that you use in both cases aren't any different though.

The source code can be downloaded from here: LambdaExpressionsDemo.zip (,87 KB)

Thursday, August 09, 2007 7:15:43 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -

 Tuesday, July 10, 2007

This is the first post in a series of xx that will be about the preparation of a presentation for my HintTech colleagues, 'LINQ and the related new features of .NET 3.5'. Today I start with the feature Extension Methods.

In the C# 3.0 Specification Extension Methods is defined as 'static methods that can be invoked using instance method syntax, which make it possible to extend existing types and constructed types with additional methods'. In a simple example of a Person class that has a Name property, you might define an Extension Method using the following syntax:

namespace ExtensionMethodDemo.Domain.Extensions { public static class PersonExtensions { public static void SayGoodbye(this Person person) { Console.WriteLine(person.Name + " : Goodbye"); } } }

Note that both the class and the method are declared as static and that the (first) parameter is defined as 'this Person person', which defines the type to which the extension method applies. When you invoke this method 'the difficult' way:

ExtensionMethodDemo.Domain.Extensions.PersonExtensions.SayGoodbye(person);

there is basically nothing new to Extension Methods. Leave out the 'this' in the parameter and you can do the same in .NET 1.0, 1.1 and 2.0. As with normal static methods, Extension Methods also have the same limitations, ie. you only have access to the public's of the Person class.

One of the powers of Extension Methods is that (after you import the namespace) the extended method appears as an instance method, so you can invoke it directly on the instance of a class:

person.SayGoodbye();

It even appears in the IntelliSense, with an indication that it is an extension to the original class. Taking into account that Extension Methods can also be applied on all .NET Framework classes (including object, string, etc.), you can imagine that some really powerful stuff is possible. For example you might have a look at the In() example of Scott Guthrie, which is an extension method to object.

Besides using Extension Methods on existing classes it is also possible to create shared interface implementations. Using this you can implement a general part of an interface using Extension Methods, which can avoid duplicate code in classes that implement the interface while clients have access to all the methods. 

In the example below an interface is defined that is extended by a shared interface implementation. Doing this the Person class only has to implement SaySomething and clients have access to both methods SaySomething and SayHello through the interface IPerson:

public interface IPerson { void SaySomething(string text); } namespace ExtensionMethodDemo.Domain.Extensions { public static class PersonExtensions { public static void SayHello(this IPerson person) { person.SaySomething("Hello"); } } }

In relation to LINQ the feature of Extension Methods is used for the extensions on IEnumerable<T> and IQueryable<T>, for example the Where() method. The advantage of implementing this as Extension Methods is that you only have the methods  in scope when you use LINQ, not when you just need the interface.

The source code can be downloaded from here: ExtensionMethodSample.zip (,57 KB)

Tuesday, July 10, 2007 8:47:26 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -

Archive
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010
Michel van der Vlugt
Sign In
All Content © 2010, Michel van der Vlugt
DasBlog theme 'Business' created by Christoph De Baene (delarou)