Action based request encoding in ASP.NET MVC

Posted by Siim on June 12th, 2012

Sometimes it’s needed to set different request/response encoding for some of the requests. For example when some third party sends requests (or responses) in some predefined encoding and doesn’t support UTF8, whereas ASP.NET uses UTF8 for all requests and responses by default.

ASP.NET allows us to change that encoding through web.config’s <globalization /> element, like:

<globalization requestEncoding="ISO-8859-1" responseEncoding="ISO-8859-1" />

But this way it affects all the request and that’s not what I want. Luckily, ASP.NET allows web.config file inheritance, by creating separate web.config file in a subfolder or using <location path=””> element in main web.config file.

In case of webforms it’s simple – we need to create location-based configuration for one of our .aspx files. But how to achieve it with MVC you might ask?

Actually, it’s exactly the same. For path part you need to provide full route url to you action. Path attribute doesn’t need to be a physical file or folder, but path in the sense of url. Only drawback is that when changing routes you must remember to change it in the web.config also. And here is the final result, which affects only one action:

<configuration>
...
<location path="path/to/your/actionmethod">
	<system.web>
		<globalization requestEncoding="ISO-8859-1" responseEncoding="ISO-8859-1" />
	</system.web>
</location>
...
</configuration>

WPF AutoCompleteBox–filtering similar items

Posted by Siim on May 30th, 2012

WPF toolkit (from Codeplex) includes a nice control for auto-complete textboxes. It supports also objects as items, not just strings. So we have a concept of selected item. Items can be filtered by simple string comparison (using simple built-in string based filters) or by defining custom filter which can use multiple properties (or whatever you like) to filter items. All these support XAML bindings so it’s all fine.

This allows us to use list of complex items as items source and use different properties for filtering, displaying items in drop-down list and displaying selected item in text box. For example, say we need to select a person from autocomplete and display only person’s last name in text box. But when user chooses person from autocomplete dropdown she wants to see person’s full name (and maybe some other properties) also so she can distinguish between persons. And lets say user wants to search by person’s nicknames also (meaning that when filtering results, we need to check person’s nicknames also). Okay, so far all good. We define custom ItemFilter and create binding for SelectedItem property and when we make a choice we can access selected item.

Problem occurs when there are multiple items with same display values (in our case multiple persons with the same last name). This triggers some weird behaviors on autocomplete side. We can see different persons in drop-down, make a selection and SelectedItem updates accordingly. But when drop-down closes, it looses currently selected item and starts finding it again from the items source based on the text in the text box. Because we have multiple persons with same last name, it selects first one it finds. And selected item is not what user chose, anymore.

Seems it’s quite well known problem based on google, but I didn’t find any solution that I really like. So it was time to dig into the source code. My idea was to create a separate property for my selected item (I call it RealSelectedItem), which behaves similarly to original SelectedItem, so it has also it’s own change events and so forth and I can directly bind to this property. Only problem is to find a proper place to update this property, so I can control when it’s updated and when not.

After digging through source, I found an interesting peace – ISelectionAdapter, which seems to be responsible for selection in drop-down only, sounds like a good place to start. It had events for commiting and cancelling selection, so I can get notifications when selection is changed. I overrode GetSelectionAdapterPart() method (which creates and returns ISelectionAdapter) and attached my methods to Commit and Cancel events when I update my RealSelectedItem property based on the SelectedItem. Full source here:

public class MyAutoCompleteBox : AutoCompleteBox
{
	public object SelectedRealItem
	{
		get { return GetValue(SelectedRealItemProperty); }
		set { SetValue(SelectedRealItemProperty, value); }
	}

	public static readonly DependencyProperty SelectedRealItemProperty =
		DependencyProperty.Register(
			&quot;SelectedRealItem&quot;,
			typeof(object),
			typeof(MyAutoCompleteBox),
			new PropertyMetadata(OnSelectedRealItemPropertyChanged));

	private static void OnSelectedRealItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		var source = d as MyAutoCompleteBox;
		source.SelectedItem = e.NewValue;
		if (e.NewValue == null)
		{
			source.Text = null;
		}

		var removed = new List&lt;object&gt;();
		if (e.OldValue != null)
		{
			removed.Add(e.OldValue);
		}

		var added = new List&lt;object&gt;();
		if (e.NewValue != null)
		{
			added.Add(e.NewValue);
		}

		source.OnRealSelectionChanged(new SelectionChangedEventArgs(SelectionChangedEvent, removed, added));
	}

	protected virtual void OnRealSelectionChanged(SelectionChangedEventArgs e)
	{
		RaiseEvent(e);
	}

	public static readonly RoutedEvent RealSelectionChangedEvent = EventManager.RegisterRoutedEvent(&quot;RealSelectionChanged&quot;, RoutingStrategy.Bubble, typeof(SelectionChangedEventHandler), typeof(MyAutoCompleteBox));

	public event SelectionChangedEventHandler RealSelectionChanged
	{
		add { AddHandler(RealSelectionChangedEvent, value); }
		remove { RemoveHandler(RealSelectionChangedEvent, value); }
	}

	protected override ISelectionAdapter GetSelectionAdapterPart()
	{
		var adapter = base.GetSelectionAdapterPart();
		adapter.Commit += (o, a) =&gt; UpdateSelectedValue(adapter.SelectedItem);
		adapter.Cancel += (o, a) =&gt; UpdateSelectedValue(null);
		return adapter;
	}

	private void UpdateSelectedValue(object value)
	{
		SelectedRealItem = value;
	}
}

Seems to work perfectly fine so far, with or without custom item template for drop down. Though, it doesn’t update RealSelectedItem when user navigates through items (like it is with SelectedItem), but I don’t need that anyway. I only want to know when user made up her mind and selection is made.

For Caliburn I needed to add my own element convention to use x:Name binding convention (actually it was already there, only for SelectedItem property), its basically one-liner (btw Caliburn doesn’t include convention for original SelectedItem either):

ConventionManager.AddElementConvention&lt;AsyncAutoCompleteBox&gt;(AsyncAutoCompleteBox.SelectedRealItemProperty, &quot;SelectedRealItem&quot;, &quot;RealSelectionChanged&quot;)
				.ApplyBinding = (viewModelType, path, property, element, convention) =&gt; ConventionManager.SetBinding(viewModelType, path, property, element, convention);

Simplifying ASP.NET MVC controllers with custom action results

Posted by Siim on February 2nd, 2011

When I am developing MVC applications I see that there are some common behavior for certain types of actions (eg. list view, edit view) which means similar code. A common solution to that problem is to create a base controller with that behavior. And that’s also how I tried to solve the problem first. I created base controllers for each view type and their related actions. But it created new problems.

I ended up with a multi-level inheritance tree which made it difficult to track down things. It wasn’t possible to look at the controller and simply say what it is doing. Some of the actions were defined at the upper level that required implementations at the lower level and so on, which created a lot of jumping between classes.
And then there was a common inheritance problem – I needed some behavior from base controller but not all, so I had to implement methods I really didn’t need. Or I needed behavior from multiple base controllers.
Third, it created a big constructors in controllers with all different dependencies required by base controller classes.

I thought about using approach called controllerless actions, but after a little research I found it is too complicated with a given structure. Luckily I can create custom action results that can encapsulate all the logic and data for returning a result for given action. But then I found this post which described separating WHAT of an action result from the HOW. By that I mean that my custom action result contains all the required information to execute an action, but the execution logic is in different object – in an action result invoker I created.

By using this approach I was able to separate all that execution logic from base controllers to separate action invoker. And controller was only responsible for returning a proper action method result with all relevant information based on the input. No repetitive execution logic anymore. For that, I created a base ActionMethodResult which is so called marker base class for my custom action method results.

public abstract class ActionMethodResult : ActionResult
{
	public override void ExecuteResult(ControllerContext context)
	{
		throw new InvalidOperationException("Action should be executed through action invoker");
	}
}

A one simple action method result implementation looks like this. It contains a task to execute and a result to return when task execution was successful and other one for failure cases.

public class TaskActionResult<TEntity> : ActionMethodResult
	where TEntity : IEntity<int>
{
	private readonly Func<ITask<TEntity>> _task;
	private readonly Func<TaskResult<TEntity>, ActionResult> _successContinuation;
	private readonly Func<TaskResult<TEntity>, ActionResult> _failureContinuation;

	public TaskActionResult(Func<ITask<TEntity>> task, Func<TaskResult<TEntity>, ActionResult> successContinuation, Func<TaskResult<TEntity>, ActionResult> failureContinuation)
	{
		_task = task;
		_successContinuation = successContinuation;
		_failureContinuation = failureContinuation;
	}

	public Func<ITask<TEntity>> Task
	{
		get { return _task; }
	}

	public Func<TaskResult<TEntity>, ActionResult> SuccessContinuation
	{
		get { return _successContinuation; }
	}

	public Func<TaskResult<TEntity>, ActionResult> FailureContinuation
	{
		get { return _failureContinuation; }
	}
}

But it’s not the case with all action results. Some of them just take some inputs and invoker decides how to respond to that. The main point is the same – invoker generates some response based on the given action method result in the context of current request. Action invoker for TaskActionResult is like this.

public class TaskActionResultInvoker<TEntity> : ITaskActionMethodResultInvoker<TEntity>
	where TEntity : IEntity<int>
{
	public ActionResult Invoke(TaskActionResult<TEntity> actionResult, ControllerContext controllerContext)
	{
		if (!controllerContext.Controller.ViewData.ModelState.IsValid)
		{
			return actionResult.FailureContinuation(null);
		}

		var result = actionResult.Task().Run();
		if (!result.ValidationResults.IsValid)
		{
			result.ValidationResults.AddToModelState(controllerContext.Controller.ViewData.ModelState);
			return actionResult.FailureContinuation(result);
		}

		return actionResult.SuccessContinuation(result);
	}
}

Then I created a custom IActionInvoker where I overrode the CreateActionResult method to create a proper ActionResult based on my custom action method result. Each of my action invoker held it’s own dependencies so I needed to create a façade for that which got my action invoker as a constructor argument so it could be resolved by my container. The creation of the facades and action invokers is a bit tedious, but it was a compromise I was willing ta make.

public class InjectingActionInvoker : ControllerActionInvoker, IActionMethodResultCreator
{
	private readonly IServiceLocator _serviceLocator;

	public InjectingActionInvoker(IServiceLocator serviceLocator)
	{
		_serviceLocator = serviceLocator;
	}

	protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
	{
		if (IsActionMethodResult(actionReturnValue))
		{
			var result = CreateActionMethodResult(actionReturnValue, controllerContext);

			return IsActionMethodResult(result)
				? CreateActionResult(controllerContext, actionDescriptor, result)
				: result;
		}
		return base.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue);
	}

	public ActionResult CreateActionMethodResult(object actionReturnValue, ControllerContext controllerContext)
	{
		var wrappedResultType = CreateActionInvokerFacadeType(actionReturnValue);

		var invokerFacade = (IActionMethodResultInvoker)_serviceLocator.Resolve(wrappedResultType);

		return invokerFacade.Invoke(actionReturnValue, controllerContext);
	}

	private static Type CreateActionInvokerFacadeType(object actionReturnValue)
	{
		var actionMethodResultType = actionReturnValue.GetType();

		Type openWrappedType;
		Type wrappedResultType;

		if (actionMethodResultType.IsGenericImplementation(typeof(TaskActionResult<>)))
		{
			openWrappedType = typeof(TaskActionResultInvokerInvokerFacade<>);
			wrappedResultType = openWrappedType.MakeGenericType(actionMethodResultType.GetGenericArguments()[0]);
		}
		// code for other types of action results removed for brevity
		else
		{
			openWrappedType = typeof(ActionMethodResultInvokerFacade<>);
			wrappedResultType = openWrappedType.MakeGenericType(actionMethodResultType);
		}

		return wrappedResultType;
	}
}

Note the recursive call to the CreateActionResult method. It is because my action method results my return other action method results for some execution paths, which in turn need to be invoked with their own type of invokers. So invokers are executed so long as result is “regular” ActionResult which can be executed using ASP.NET MVC built-in behavior. 

Finally, when all hooked up, my controller action looks like this. Simple, clean and without inheritance.

[HttpPost]
public ActionResult Edit(int id, ViewModel item)
{
	item.Id = id;

	return new TaskActionResult<Entity>(
		() => _taskFactory.ForSave(() => CreateEntityFromViewModel(item)),
		success => SaveSuccessResult(success, "Task executed!"),
		SaveFailureResult);
}

Now I’m able to create much more simple controllers in the maintenance point of view, they are better to follow. It also improved testability. Because in my opinion, inheritance is pain in the butt regarding testing. This approach allowed me to easily test the result of the controller action (which is basically a plain data) separately from the execution of that result. Which I can do in an isolation compared to the approach when I was using controller inheritance which also resulted in some sort of tests inheritance.

Storing files and metadata with NHibernate

Posted by Siim on September 21st, 2010

Now and then there comes a need to save some documents to the database also, along with the other information stored there already. It’s not a big deal to save some additional files to the database, especially when it’s not the main purpose of the application, just some extra. So no need for different storage mechanism.

This time I’m using NHibernate and I thought how I should structure tables and write mappings so that files data gets loaded only then when I really need it (eg. downloading a file). I also save some metadata about the file, some if it has business meaning, some of it doesn’t.

Database

I came up with the following simple schema:

clip_image001

I can load all the related meta-info about the file easily without touching the real content. That kind of schema also allows us to put FILE_DATA table to a different file group in MS SQL Server, so physically it can be located on other drive or partition whereas files metadata is located with our other tables.

Mappings

But this is only database side, there are also NHibernate mappings we have to work on. From NHibernate point of view, it’s not one-to-one relation but more like an one-to-many relation, meaning that File may have 0 or more FileData objects. So internally I mapped it like so, but to the outside I exposed it like one-to-one. I am using FluentNhibernate and here are my mappings for that:

public class FileMap : ClassMap<File>
{
	public FileMap()
	{
		DiscriminateSubClassesOnColumn("FILE_TYPE");

		Id(x => x.Id);
		Map(x => x.Type, "FILE_TYPE")
			.ReadOnly();
		Map(x => x.Name);
		Map(x => x.ContentType);

		HasMany<FileData>(Reveal.Member<File>("_files"))
			.Access.Field()
			.Cascade.AllDeleteOrphan()
			.Inverse();
	}
}

public class FileDataMap : ClassMap<FileData>
{
	public FileDataMap()
	{
		Id(x => x.Id);
		Map(x => x.Content);
		References(x => x.File);
	}
}

And related objects:

public abstract class File : IntegerIdentityEntity
{
	private IList<FileData> _files;

	protected File()
	{
		_files = new List<FileData>();
	}

	protected virtual IList<FileData> Files
	{
		get { return _files; }
	}

	protected virtual FileData FileData
	{
		get { return Files.SingleOrDefault(); }
	}

	public virtual string Type { get; protected set; }

	public virtual string Name { get; set; }

	public virtual string Number { get; set; }

	public virtual string ContentType { get; set; }

	public virtual byte[] Data
	{
		get
		{
			return FileData != null ? FileData.Content : null;
		}
		set
		{
			if (FileData != null && value == null)
			{
				FileData.File = null;
				Files.Remove(FileData);
			}
			else if(FileData != null)
			{
				FileData.Content = value;
			}
			else if(value != null)
			{
				var dataFile = new FileData {File = this, Content = value};
				Files.Add(dataFile);
			}
		}
	}
}

public class FileData : IntegerIdentityEntity,
{
	public virtual File File { get; set; }

	public virtual byte[] Content { get; set; }
}

As you can see, externally there is only one object – File, with property Data which returns the contents of the file as a byte array. Internally it is stored in the FileData collection because it’s the natural way how NHibernate handles such scenarios but that doesn’t mean we must always expose it as collection.

Conclusion

This approach allows to store files and their metadata in a database in a simple way, without adding any extra overload to fetching when it’s not necessary. From a database perspective it don’t add any extra constraints either, because we can put data table to a different partition so keeping the size of the main database reasonable.

ASP.NET MVC RenderAction with action method overloads

Posted by Siim on September 5th, 2010

In ASP.NET MVC, every controller method which is public and not marked with NonAction attribute is considered as an action. And action name is the same as method name. But you can also provide ActionName attribute with specified action name. There is also different attributes to constrain actions to handle only specified HTTP methods (GET, POST, PUT etc). All that information is used when finding which controller method to execute.

So, when technically (in a sense of C#) you can create many method overloads for a controller method, you end up with runtime exception when you don’t further restrain those actions. For example, consider following controller:

public class ProductController : Controller
{
	public ActionResult Edit(int id)
	{
		return View("Edit");
	}

	public ActionResult Edit(int id, ProductItem item)
	{
		return View("EditPost");
	}
}

public class ProductItem
{
	public int Id { get; set; }

	public string Name { get; set; }
}

When executing Edit action, MVC don’t know which method overload to execute, because current route could be handled by both of the Edit methods. But when decorating first method with HttpGet attribute and the second with HttpPost attribute, it works well.

Now, the trouble comes when you execute one of such methods from the view with RenderAtion method. Lets say you have two controllers:

public class ProductController : Controller
{
	public ActionResult Edit(int id)
	{
		return View("Edit");
	}

	[HttpPost]
	public ActionResult Edit(int id, ProductItem item)
	{
		return View("EditPost");
	}
}

public class ProductDetailController : Controller
{
	public ActionResult Edit(int id)
	{
		return View("EditDetail");
	}

	[HttpPost]
	public ActionResult Edit(int id, ProductDetailItem item)
	{
		return View("EditDetailPost");
	}
}

public class ProductDetailItem
{
	public string Type { get; set; }
}

public class ProductItem
{
	public int Id { get; set; }

	public string Name { get; set; }
}

ProductController is used to display product form view. On that form, I also call RenderAction to render Edit method on the ProductDetailController which displays some product sub-detail form. When executing first ProductController.Edit method, all works fine. When I submit product form, then the second Edit method is executed (because it handles POST requests).

At first, it looked like some weird behavior. But after when I gave a thought how MVC resolves which action method to execute, it all works out. It’s because RenderAction uses the same algorithm to resolve actions as a regular action link. So pay attention when using same pattern with controllers and actions.

MvcContrib grid with extended sorting capabilities

Posted by Siim on July 7th, 2010

Lately I’ve been doing development on ASP.NET MVC and using MvcContrib grid to render simple grids. I have to say, it is very easy to use and extendible in every way. If I feel that something is missing or I want to change some behavior, then I just need to implement the proper interfaces and inject my own implementation for what I need.

For views I use view models with data annotations which specify how some data should be displayed on the view. I wanted to use data annotations also for specifying which properties should be rendered as sortable columns and which is the default one. Grid doesn’t do any sorting by itself, it solely relies on the input (which is a good thing, IMHO).

Fortunately, it was very easy to add. I needed only two things – customize the MVC model metadata provider to include my custom values and create a custom ColumnBuilder for the grid that could read values I included in the metadata. Brad Wilson has a nice post about how to extend model metadata providers. The code for the OrderByAttribute and with the bit that extends model metadata, is here:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class OrderByAttribute : Attribute
{
	public OrderByAttribute()
		: this(SortDirection.Ascending, false)
	{
	}

	public OrderByAttribute(SortDirection sortOrder, bool isDefault)
	{
		SortOrder = sortOrder;
		IsDefault = isDefault;
	}

	public SortDirection SortOrder { get; set; }

	public bool IsDefault { get; set; }
}

public class GridMetaDataProvider : DataAnnotationsModelMetadataProvider
{
	public const string SortableValueName = "Sortable";

	protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
		Func<object> modelAccessor, Type modelType, string propertyName)
	{
		var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

		var orderByAttribute = attributes.OfType<OrderByAttribute>().FirstOrDefault();
		if (orderByAttribute!=null)
		{
			metadata.AdditionalValues.Add(SortableValueName, orderByAttribute);
		}

		return metadata;
	}
}

Next I need to create a column builder, similarly to AutoColumnBuilder which comes with MvcContrib. Unfortunately, I cannot extend that class because there are no extension point, but I used it as a guidance. For each property from metadata, I execute the following code, to apply sorting metadata:

var isSortable = property.AdditionalValues.ContainsKey(GridMetaDataProvider.SortableValueName);
column.Sortable(isSortable);
column.SortColumnName(property.PropertyName);

That’s all about building columns from metadata. Next thing I need to do, is to tell the grid which column is used for initial sorting. Because grid wants object of type GridSortOptions as an input, it is created by the controller. So I wrote a little extension method to populate GridSortOptions from model metadata.

public static GridSortOptions ApplyDefault<TItem>(this GridSortOptions sortOptions) where TItem : ListItemBase
{
	// When sort options is specified, don't apply default values
	if (sortOptions != null && !string.IsNullOrEmpty(sortOptions.Column)) return sortOptions;

	var property = typeof (TItem).GetProperties().Where(ContainsDefaultOrderBy).FirstOrDefault();
	if (property == null) return sortOptions;

	var newSortOptions = sortOptions ?? new GridSortOptions();
	newSortOptions.Column = property.Name;
	return newSortOptions;
}

private static bool ContainsDefaultOrderBy(PropertyInfo property)
{
	var orderBy = (OrderByAttribute)property.GetCustomAttributes(typeof (OrderByAttribute), false).FirstOrDefault();
	return orderBy != null && orderBy.IsDefault;
}

That’s it. Now you can decorate your view model with attributes and grid takes care of the rest.

Querying localized values in NHibernate

Posted by Siim on March 30th, 2010

In my previous post I talked about how to create model for localized values. Now it’s time to show how I’m querying against that model.

I display language selection to the user. So all localizable data is preferably shown in the language the user chose. When displaying persons list, for example, person name is shown in the language the user chose or the first available localized value if the localization for chosen language was not found. I’ll use HQL queries for that, which return a projection from entity to DTO to contain only data I need. HQL allows better (and easier) optimization than using criteria and it’s easier to write.

So HQL that returns persons list where first name and last name are localized, looks like this:

select distinct new PersonDataContract(person.Id, firstName.Value, lastName.Value, person.ContactCard.Phone, person.ContactCard.Mobile,
	person.ContactCard.Email.Address, l.id, firstName.Language.id, lastName.Language.id)
from Language l, Person as person
	join person.FirstName tfname
	left outer join tfname.Localizations firstName
	join person.LastName tlname
	left outer join tlname.Localizations lastName
where l.id = :langId
	and (firstName.Language.id = l.id or (index(firstName) = 0 and l.id not in (select loc.Language.id from Localization loc where loc.Translation = tfname)))
	and (lastName.Language.id = l.id or (index(lastName) = 0 and l.id not in (select loc.Language.id from Localization loc where loc.Translation = tlname)))
order by lastName.Value, firstName.Value 

I also fetch the language id for localized values because I want to show to the user if returned value was in language he requested.

And matching SQL from NHProf:

persons_query

When an object has many localizable properties then such a query could become too complex, too many joins. In that case it may be better to use different strategy for fetching objects. We can use NHibernate’s multi queries or Futures. I’ll show you similar example, but in a bit different context.

In some situations it would be better to show to user all translations for selected language in a single list. For example when there is a language specialist to translate all values from one language to another. In that case we need to load all translations (for specified context, eg. person names) with localizations. In this case I need also to use paging to limit the result set.

I use multi queries approach here. First I fetch translations for the selected context and languages list. And for each language I load localizations for translations in separate queries. So I make total of two roundtrips to the database.

 public IEnumerable<Translation> GetTranslationsBy(Type translationType, int startItemIndex, int numberOfItems)
{
	// Select IDs first
	var idQuery =
		Session.CreateQuery("select t.id from Translation t where t.class = " + translationType.FullName)
			.SetFirstResult(startItemIndex)
			.SetMaxResults(numberOfItems);
	var temporaryList = Session.CreateMultiQuery()
		.Add(idQuery)
		.Add("from Language").List();

	const string queryFormat = "from Translation t left join fetch t.Localizations l where t.class = {0} and l.Language.id = :{1} and t.id in (:translationIds)";

	var multiQuery = Session.CreateMultiQuery();
	foreach (Language language in (ArrayList)temporaryList[1])
	{
		var langParamName = string.Format("lang{0}Id", language.Id);
		var query = Session.CreateQuery(string.Format(queryFormat, translationType, langParamName))
			.SetInt32(langParamName, language.Id);
		multiQuery.Add(query);
	}
	multiQuery.SetParameterList("translationIds", (ArrayList) temporaryList[0]);

	IEnumerable<Translation> result = new List<Translation>();
	var list = multiQuery.List();
	if (list.Count > 0)
	{
		result = (IEnumerable<Translation>)((ArrayList)list[0]).ToArray(translationType);
	}
	return result;
}

repository.GetTranslationsBy(typeof (PartnerNameTranslation), 0, 10); 

With results:

translations_queries

translations_query1

translations_query2

The third query is similar to the first two, only for different language.

I’m using only the first result set from the second batch. Other queries are only for fetching all available localizations for translations and actual results they return, will be discarded. That way I pre-load all the values and therefore there is no need for lazy loading them which in turn would result in executing multiple queries to the database.

As I mentioned, the last approach may also be used when loading DTO’s, only in that case mapping to DTO should be done by the user (or use AutoMapper in some extent).


Copyright © 2007 Siim Viikman's blog.