Skip to content

David Turvey's Blog

All About Development

Archive

Category: .NET 3.5

Normally when you commit a change to the database using LINQ it will generate SQL to perform the insert/update/delete action. Most of the time this is fine, but LINQ does provide the ability to override this behaviour and specify a stored procedure that should be executed instead of the default behaviour. And luckily it’s really easy.

First, create your stored procedure, normally if you are creating an insert or update stored procedure the proc will have a parameter for each field but this is not a requirement as you can map the individual fields to the properties of the class.

Drag the stored procedure onto your DBML so that the LINQ framework creates a method for the stored procedure, in this example the stored procedure is called InsertLessee.

LINQInsert1

Then right click on the LINQ entity in the DBML and select Configure Behaviour.

LINQInsert2

Then (1) choose the behaviour to replace, (2) select Customize and select the stored procedure from the drop down list, in this case InsertLessee, and (3) if needed alter the stored procedure parameter to class property mapping.

LINQInsert3

It is as simple as that, now whenever a Lessee is inserted the LINQ framework will call the stored procedure instead of generating SQL at runtime.

Anonymous Types and Implicitly Typed Local Variables are two new features to the .Net 3.5 framework that work hand in hand and are used mainly with LINQ.

Anonymous Typing allows you to create a class without explictly defining the class, for example say you needed a class that contained the properties FirstName and LastName but you were only going to use it inside a single method and you didn’t want to define a class just for a one off usage.

Using anonymous typing you could create the class as follows:

var person = new {FirstName = "John", LastName = "Smit"}

Implicitly Typed Local Variable allows variables to be declared without having to specify the type at design-time. The strong-type assigned to the variable is inferred at compile-time from the initialization expression. This gives you some of the benefits of a dynamic type with the advantages of compile time checking.

So if the following Implicitly Typed Local Variables were declared:
(The var keyword denotes an Implicitly Typed Local Variable)

var person = new {FirstName = "John", LastName = "Smit"}
var num = 5;
var str = “Example”;

The compiler will know that the variable person is an object with the properties FirstName and LastName, and that num is an integer and str is a string. Basically whatever is on the right hand side of the equal sign defines the type of the variable. Once the variable has been declared it is type safe, so you won’t be able to assign the incorrect type to it or call members on it that don’t exist, in those cases a compile time error will occur.

The major use for Anonymous Types and Implicitly Typed Local Variables is with LINQ, when performing a LINQ query you may want to return information from multiple objects into a single object, now instead of having to create a class defining the properties you want to return from the query you can use Anonymous Types and Implicitly Typed Local Variables.

For example:

var cities = from city in Cities
             join state in States on city.State equals state
             select new
             {
                 CityName = city.Name,
                 StateName = state.Name
             };

In this example I only want to retrieve the city name and state name, but the properties I want are on two objects so I create a new anonymous type which is assigned to an implicitly typed local variable.

There are a couple of important restrictions when using the var keyword:

  • The declaration must have an initializer that the compiler can resolve to a type definition.
  • The initializer expression cannot evaluate to null. The compiler must be able to determine the type.
  • A type called var cannot be in the same scope, otherwise it is used.
  • The var keyword must only be used for local variable declaration.

Disclaimer: This post is based on Orcas CTP June 2007

A very simple and awesome new feature in 3.5 is Automatic Properties, the basic idea is that you just define the property name and the visibility of the getter and setter. No need to specify the private field and the body of the get and set to retrieve and set the value. So the snippet below:

private EntityState _EntityState;
public EntityState EntityState
{
    get { return _EntityState; }
    private set { _EntityState = value; }
}

Would become:

public EntityState EntityState { get; private set; }

The 3.5 framework handles creating the getter, setter, and private member for you. This small addition to the framework can made your code much cleaner.

Obviously it only helps for those situations where you are just retrieving the value / setting it, if you want to do any additional processing you’ll need to create your property the old fashioned way.

Automatic properties must have get and set declared, which is obvious considering that the private member is not accessible, so all access must go through the property

Disclaimer: This post is based on Orcas CTP June 2007

A new feature in the 3.5 framework is object initializers, object initializers allow you to set the values of public properties on an object in the constructor call. In the past you would have to create the instance of the object then assign each property one by one, for example:

_DataContext = new RdmDataContext();
_DataContext.LoadOptions = options;
_DataContext.DeferredLoadingEnabled = true;

Using the new syntax you can set the properties in a single statement:

_DataContext = new RdmDataContext() { LoadOptions = options, DeferredLoadingEnabled = true };

Much cleaner! Note that you can only set the values of public properties on the object.

Disclaimer: This post is based on Orcas CTP June 2007

The LINQ to SQL entites don’t have a property that lets you know if the instance of the object has been loaded from the database or has been locally created, i.e. new.

A simple solution to this problem is to add an enumeration with the enums New and Loaded:

public enum EntityState
{
    [Description("New")]
    New = 0,

    [Description("Loaded")]
    Loaded = 1
}

Then create a property in the partial class of your LINQ to SQL entity for the enumeration:

public EntityState EntityState
{
    get { return _EntityState; }
    private set { _EntityState = value; }
}

Then in the partial method OnCreated set the property’s value to New and in the partial method OnLoaded set it to Loaded:

partial void OnCreated()
{
    EntityState = EntityState.New;
}

partial void OnLoaded()
{
    EntityState = EntityState.Loaded;
}

Now if you create a new entity only the OnCreated method will be executed, and if its loaded from the db the OnCreated will be fired and then the OnLoaded. So you can now easily determine its state.

Of course you could also check the primary key’s value against the default for its type but that is not ideal, the primary key is not nullable so for an integer primary key you would have to check if it is 0 to determine if its new or not. Rather avoid that approach.

Disclaimer: This post is based on Orcas CTP June 2007