Member Aliasing in Linq2Rest

Tags: Linq2Rest

A recent issue was raised for Linq2Rest where aliased properties are not supported when generating the OData style query URL. I pushed changes to the library which should now include support for member aliasing.

Why is aliasing interesting? The .NET framework lets you customize the serialization of your objects using different attributes (DataMember, XmlElement, XmlAttribute). These attributes make it possible to assign a custom serialization name to a particular member so that it matches what is defined by the external system. The same can used when be used when querying a remote server. It may be exposing a data structure with a given set of names which does not match the names that you wish to use in your application. If you wish to serialize data to pass to the remote system you will need to do it using the remote name definitions, hence the attributes. The same applies when you are querying data on a remote system - you have to use the names the remote system has defined.

So how do you make your LINQ query support this? I won't go into the details, if you are interested you can read the source code. The short story is that when parsing the expression tree of the LINQ query the member names are substituted for the remote names. If you have a look at the ItemDto below and the AliasDto, then any query against an AliasDto (which simulates a client system with a customized naming) will generate an OData style query using the ItemDto names.

public class ItemDto
	public int ID { get; set; }

	public string Text { get; set; }

public class AliasItem
	[DataMember(Name = "Text")]
	private string _stringValue;

	[DataMember(Name = "ID")]
	public int AliasID { get; set; }

	public string StringValue
			return _stringValue;

			_stringValue = value;

The following client expression tree:

x => (x.StringValue == \"a \"quote\" within the text\")

Will generate the following OData style filter:

Text eq 'a \"quote\" within the text'

and will generate the following expression tree on the remote system:

x => (x.Text == \"a \"quote\" within the text\")

One thing to notice here is that in the AliasItem class, the field is being serialized. Linq2Rest uses a convention that maps fields to properties if their names are the same when casing is ignored. Leading underscores are allowed. So (_stringValue, stringValue would match the StringValue property). If you stick to this convention you can make use of the support for field serialization in DataContracts.

Aliasing is supported from version 4 (currently in beta). You can follow the project at BitBucket.

Latest Tweets