Currently I'm working with a system handling different operations when receiving business documents in object form. Its quite obvious that the code for handling this has evolved to have a lot more responsibilities than it was intended to.
So already having an Inversion of Control container in our stack I thought we could make the operations in the pipeline configurable using the container. To achieve this we need to specify an interface for the tasks in the pipeline, in our case its pretty simple:
public interface IPipelineTask<T>
{
T Perform(T instance);
}
Secondly we need to define the pipeline itself, again using a generic interface:
public interface IPipeline<T>
{
T Execute(T instance);
}
So basically what I want to accomplish is the ability to ask my Inversion of control container for a pipeline for a certain type and be able to call the Execute method on the instance and have all associated tasks performed on the instance I pass to the method. So the code for handling an incoming object of type Invoice would look like this:
Invoice incomingInvoice = ....; ProjectContainer container = new ProjectContainer(); IPipeline<Invoice> pipeline = container.Resolve<IPipeline<Invoice>>(); Invoice processedInvoice = pipeline.Execute(incomingInvoice); container.Release(pipeline);
So lets look at the implementation of the generic pipeline that handles executing of each task:
public class Pipeline<T> : IPipeline<T>
{
private IPipelineTask<T>[] tasks;
public Pipeline(IPipelineTask<T>[] pipelinetasks)
{
tasks = pipelinetasks;
}
public T Execute(T instance)
{
T processedInstance = instance;
foreach (var task in tasks)
{
processedInstance = task.Perform(processedInstance);
}
return processedInstance;
}
}
Note the constructor takes an array of IPipelineTasks<T> this is here our Inversion of Control container comes to play and does this for us using constructor dependency injection.
Each task needs to implement the IPipelineTask<T> with its specific business object type:
public class InvoiceNotifier : IPipelineTask<Invoice>
{
private IUserNotifier usernotifier;
public InvoiceNotifier(IUserNotifier notifier)
{
usernotifier = notifier;
}
public Invoice Perform(Invoice instance)
{
usernotifier.Notify(Notification.IncomingInvoice,
"The invoice with identifier " + instance.ID + " changed state to " + instance.State);
return instance;
}
}
Normally when working with arrays in Castle Windsor we have to specify each service to be part of the array in the configuration, however in our case we want all registered implementations of the specific interface to be passed to the pipeline. To do this we can add a custom sub dependency resolver to castle, in fact we can use the ArraySubDependencyResolver already written by Castle projects founder (and soon to be Microsoftee) Hammett. With this in place we can make the following configuration and our mission is accomplished and all tasks registered in the configuration will be injected when we request the generic Pipeline of this type.
<components>
<!--Register the generic pipeline-->
<component
id="bussiness.document.pipeline"
service="Services.IPipeline`1, Services"
type="Services.Pipeline`1, Services"
lifetype="Thread"
/>
<!--Register our pipeline tasks-->
<component
id="invoice.notification"
service="Services.IPipelineTask`1[[Domain.Invoice, Domain]], Services"
type="Services.InvoiceNotifier, Services"
lifetype="Thread"
/>
<component
id="invoice.reciever"
service="Services.IPipelineTask`1[[Domain.Invoice, Domain]], Services"
type="Services.InvoiceReciever, Services"
lifetype="Thread"
/>
<!--Registration of services and repositories which our pipeline tasks uses-->
....
</components>
Using this infrastructure custom tasks can be specified easily in the configuration even from other namespaces and assemblies. And the pipeline doesn't need to worry about the dependencies of each Pipeline task, the container handles this
Currently I'm working with a system handling different operations when receiving business documents in object form. Its quite obvious that the code for handling this has evolved to have a lot more responsibilities than it was intended to.
So already having an Inversion of Control container in our stack I thought we could make the operations in the pipeline configurable using the container. To achieve this we need to specify an interface for the tasks in the pipeline, in our case its pretty simple:
public interface IPipelineTask<T>
{
T Perform(T instance);
}
Secondly we need to define the pipeline itself, again using a generic interface:
public interface IPipeline<T>
{
T Execute(T instance);
}
So basically what I want to accomplish is the ability to ask my Inversion of control container for a pipeline for a certain type and be able to call the Execute method on the instance and have all associated tasks performed on the instance I pass to the method. So the code for handling an incoming object of type Invoice would look like this:
Invoice incomingInvoice = ....; ProjectContainer container = new ProjectContainer(); IPipeline<Invoice> pipeline = container.Resolve<IPipeline<Invoice>>(); Invoice processedInvoice = pipeline.Execute(incomingInvoice); container.Release(pipeline);
So lets look at the implementation of the generic pipeline that handles executing of each task:
public class Pipeline<T> : IPipeline<T>
{
private IPipelineTask<T>[] tasks;
public Pipeline(IPipelineTask<T>[] pipelinetasks)
{
tasks = pipelinetasks;
}
public T Execute(T instance)
{
T processedInstance = instance;
foreach (var task in tasks)
{
processedInstance = task.Perform(processedInstance);
}
return processedInstance;
}
}
Note the constructor takes an array of IPipelineTasks<T> this is here our Inversion of Control container comes to play and does this for us using constructor dependency injection.
Each task needs to implement the IPipelineTask<T> with its specific business object type:
public class InvoiceNotifier : IPipelineTask<Invoice>
{
private IUserNotifier usernotifier;
public InvoiceNotifier(IUserNotifier notifier)
{
usernotifier = notifier;
}
public Invoice Perform(Invoice instance)
{
usernotifier.Notify(Notification.IncomingInvoice,
"The invoice with identifier " + instance.ID + " changed state to " + instance.State);
return instance;
}
}
Normally when working with arrays in Castle Windsor we have to specify each service to be part of the array in the configuration, however in our case we want all registered implementations of the specific interface to be passed to the pipeline. To do this we can add a custom sub dependency resolver to castle, in fact we can use the ArraySubDependencyResolver already written by Castle projects founder (and soon to be Microsoftee) Hammett. With this in place we can make the following configuration and our mission is accomplished and all tasks registered in the configuration will be injected when we request the generic Pipeline of this type.
<components>
<!--Register the generic pipeline-->
<component
id="bussiness.document.pipeline"
service="Services.IPipeline`1, Services"
type="Services.Pipeline`1, Services"
lifetype="Thread"
/>
<!--Register our pipeline tasks-->
<component
id="invoice.notification"
service="Services.IPipelineTask`1[[Domain.Invoice, Domain]], Services"
type="Services.InvoiceNotifier, Services"
lifetype="Thread"
/>
<component
id="invoice.reciever"
service="Services.IPipelineTask`1[[Domain.Invoice, Domain]], Services"
type="Services.InvoiceReciever, Services"
lifetype="Thread"
/>
<!--Registration of services and repositories which our pipeline tasks uses-->
....
</components>
Using this infrastructure custom tasks can be specified easily in the configuration even from other namespaces and assemblies. And the pipeline doesn't need to worry about the dependencies of each Pipeline task, the container handles this
Currently I'm working with a system handling different operations when receiving business documents in object form. Its quite obvious that the code for handling this has evolved to have a lot more responsibilities than it was intended to.
So already having an Inversion of Control container in our stack I thought we could make the operations in the pipeline configurable using the container. To achieve this we need to specify an interface for the tasks in the pipeline, in our case its pretty simple:
public interface IPipelineTask<T>
{
T Perform(T instance);
}
Secondly we need to define the pipeline itself, again using a generic interface:
public interface IPipeline<T>
{
T Execute(T instance);
}
So basically what I want to accomplish is the ability to ask my Inversion of control container for a pipeline for a certain type and be able to call the Execute method on the instance and have all associated tasks performed on the instance I pass to the method. So the code for handling an incoming object of type Invoice would look like this:
Invoice incomingInvoice = ....; ProjectContainer container = new ProjectContainer(); IPipeline<Invoice> pipeline = container.Resolve<IPipeline<Invoice>>(); Invoice processedInvoice = pipeline.Execute(incomingInvoice); container.Release(pipeline);
So lets look at the implementation of the generic pipeline that handles executing of each task:
public class Pipeline<T> : IPipeline<T>
{
private IPipelineTask<T>[] tasks;
public Pipeline(IPipelineTask<T>[] pipelinetasks)
{
tasks = pipelinetasks;
}
public T Execute(T instance)
{
T processedInstance = instance;
foreach (var task in tasks)
{
processedInstance = task.Perform(processedInstance);
}
return processedInstance;
}
}
Note the constructor takes an array of IPipelineTasks<T> this is here our Inversion of Control container comes to play and does this for us using constructor dependency injection.
Each task needs to implement the IPipelineTask<T> with its specific business object type:
public class InvoiceNotifier : IPipelineTask<Invoice>
{
private IUserNotifier usernotifier;
public InvoiceNotifier(IUserNotifier notifier)
{
usernotifier = notifier;
}
public Invoice Perform(Invoice instance)
{
usernotifier.Notify(Notification.IncomingInvoice,
"The invoice with identifier " + instance.ID + " changed state to " + instance.State);
return instance;
}
}
Normally when working with arrays in Castle Windsor we have to specify each service to be part of the array in the configuration, however in our case we want all registered implementations of the specific interface to be passed to the pipeline. To do this we can add a custom sub dependency resolver to castle, in fact we can use the ArraySubDependencyResolver already written by Castle projects founder (and soon to be Microsoftee) Hammett. With this in place we can make the following configuration and our mission is accomplished and all tasks registered in the configuration will be injected when we request the generic Pipeline of this type.
<components>
<!--Register the generic pipeline-->
<component
id="bussiness.document.pipeline"
service="Services.IPipeline`1, Services"
type="Services.Pipeline`1, Services"
lifetype="Thread"
/>
<!--Register our pipeline tasks-->
<component
id="invoice.notification"
service="Services.IPipelineTask`1[[Domain.Invoice, Domain]], Services"
type="Services.InvoiceNotifier, Services"
lifetype="Thread"
/>
<component
id="invoice.reciever"
service="Services.IPipelineTask`1[[Domain.Invoice, Domain]], Services"
type="Services.InvoiceReciever, Services"
lifetype="Thread"
/>
<!--Registration of services and repositories which our pipeline tasks uses-->
....
</components>
Using this infrastructure custom tasks can be specified easily in the configuration even from other namespaces and assemblies. And the pipeline doesn't need to worry about the dependencies of each Pipeline task, the container handles this
When working with object relational mapping(or even handrolled DAL's) you most often work on fully populated objects. When working in an environment utilizing Data Transfer Object either for transport over the wire or screen bound DTO's you have to slice or merge your fully populated objects. With LINQ for nHibernate, LINQ for SQL the solution for this is pretty obvious you populate the object using its constructor or object initialisers in a LINQ query either directly on your data source or on one or more already populated instances.
A quick example using LINQ for nHibernate could be:
var result = from p in db.Products select new ProductDTO {p.ID, p.Name} ;
(Of course we need to make instances not anonymous types because we need to pass them out of the current scope)
If we are stuck using traditional querying in nHibernate we can accomplish the same using HQL:
select new ProductDTO(p.ID, p.Name) from Product p
When using this HQL query its important to remember to import your DTO class in the mapping or else you will end up with an error like:
NHibernate.QueryException : class not found: ProductDTO
To import it just add <import class="Name.Space.ProductDTO, Assembly"> right after your hibernate-mapping element. Of course the generating of the DTO's can get much more complex than the samples i have shown. They could span multiple business object requiring complex queries but the concept remains the same.
Okay, so these options are valid only for folks using an LINQ empowered ORM's or frameworks with equivalent functionality to the nHibernate sample above. One thing we could do is to create the DTO's from the fully populated objects. Of course this could be a dangerous decision if you don't already have the objects in the current context and the DTO's require a very little subset of the data, so that's definitely worth noting. That beeing said we could do this in a number of ways all which i can thing of writing myself involves plumbing code. So a couple of days ago I stumbled upon a project called otis a object transformer or Object-to-Object mapper if you prefer that term.
The concept is pretty simple, we can define how one object map to another so if we take our very simple case we can specify a mapping on this form:
<?xml version="1.0" encoding="utf-8" ?>
<otis-mapping xmlns="urn:otis-mapping-1.0">
<class name="Name.Space.ProductDTO, Assembly" source="Name.Space.Product, Assembly" >
<member name="ID" />
<member name="Name" />
</class>
</otis-mapping>
In the above case we have the same names on properties in both classes so its pretty simple, but the possibilities in the mapping is many. You can use expression to combine multiple values to one, projections, exchanging certain values etc. I will certainly have to look into the source code of otis and have a look of its capabilities as the documentation is a bit sparse.
To utilize the above mapping we configure the framework and use a generic class to get Assembler classes that can convert our types, its pretty simple:
Product product = ...; //Our fully populated product instance Otis.Configuration conf = new Otis.Configuration(); //Looks for embedded ressource with *.otis.xml ending conf.AddAssemblyResources(Assembly.GetExecutingAssembly(), "otis.xml"); //Declare our assembler var asm = conf.GetAssembler<ProductDTO, Product>(); //Use the assembler to get the DTO ProductDTO dto = asm.AssembleFrom(product);
As I said I will definitely dive into the source to explore which features are available and how the transformation is done and what the costs of it is. The main issue I have with the approach is that we could do the same using code and to make it more flexible lambda expressions and have it strongly typed and avoid the verbosity of XML, but lets see how feature rich Otis is before dismissing it.
When working with object relational mapping(or even handrolled DAL's) you most often work on fully populated objects. When working in an environment utilizing Data Transfer Object either for transport over the wire or screen bound DTO's you have to slice or merge your fully populated objects. With LINQ for nHibernate, LINQ for SQL the solution for this is pretty obvious you populate the object using its constructor or object initialisers in a LINQ query either directly on your data source or on one or more already populated instances.
A quick example using LINQ for nHibernate could be:
var result = from p in db.Products select new ProductDTO {p.ID, p.Name} ;
(Of course we need to make instances not anonymous types because we need to pass them out of the current scope)
If we are stuck using traditional querying in nHibernate we can accomplish the same using HQL:
select new ProductDTO(p.ID, p.Name) from Product p
When using this HQL query its important to remember to import your DTO class in the mapping or else you will end up with an error like:
NHibernate.QueryException : class not found: ProductDTO
To import it just add <import class="Name.Space.ProductDTO, Assembly"> right after your hibernate-mapping element. Of course the generating of the DTO's can get much more complex than the samples i have shown. They could span multiple business object requiring complex queries but the concept remains the same.
Okay, so these options are valid only for folks using an LINQ empowered ORM's or frameworks with equivalent functionality to the nHibernate sample above. One thing we could do is to create the DTO's from the fully populated objects. Of course this could be a dangerous decision if you don't already have the objects in the current context and the DTO's require a very little subset of the data, so that's definitely worth noting. That beeing said we could do this in a number of ways all which i can thing of writing myself involves plumbing code. So a couple of days ago I stumbled upon a project called otis a object transformer or Object-to-Object mapper if you prefer that term.
The concept is pretty simple, we can define how one object map to another so if we take our very simple case we can specify a mapping on this form:
<?xml version="1.0" encoding="utf-8" ?>
<otis-mapping xmlns="urn:otis-mapping-1.0">
<class name="Name.Space.ProductDTO, Assembly" source="Name.Space.Product, Assembly" >
<member name="ID" />
<member name="Name" />
</class>
</otis-mapping>
In the above case we have the same names on properties in both classes so its pretty simple, but the possibilities in the mapping is many. You can use expression to combine multiple values to one, projections, exchanging certain values etc. I will certainly have to look into the source code of otis and have a look of its capabilities as the documentation is a bit sparse.
To utilize the above mapping we configure the framework and use a generic class to get Assembler classes that can convert our types, its pretty simple:
Product product = ...; //Our fully populated product instance Otis.Configuration conf = new Otis.Configuration(); //Looks for embedded ressource with *.otis.xml ending conf.AddAssemblyResources(Assembly.GetExecutingAssembly(), "otis.xml"); //Declare our assembler var asm = conf.GetAssembler<ProductDTO, Product>(); //Use the assembler to get the DTO ProductDTO dto = asm.AssembleFrom(product);
As I said I will definitely dive into the source to explore which features are available and how the transformation is done and what the costs of it is. The main issue I have with the approach is that we could do the same using code and to make it more flexible lambda expressions and have it strongly typed and avoid the verbosity of XML, but lets see how feature rich Otis is before dismissing it.
When working with object relational mapping(or even handrolled DAL's) you most often work on fully populated objects. When working in an environment utilizing Data Transfer Object either for transport over the wire or screen bound DTO's you have to slice or merge your fully populated objects. With LINQ for nHibernate, LINQ for SQL the solution for this is pretty obvious you populate the object using its constructor or object initialisers in a LINQ query either directly on your data source or on one or more already populated instances.
A quick example using LINQ for nHibernate could be:
var result = from p in db.Products select new ProductDTO {p.ID, p.Name} ;
(Of course we need to make instances not anonymous types because we need to pass them out of the current scope)
If we are stuck using traditional querying in nHibernate we can accomplish the same using HQL:
select new ProductDTO(p.ID, p.Name) from Product p
When using this HQL query its important to remember to import your DTO class in the mapping or else you will end up with an error like:
NHibernate.QueryException : class not found: ProductDTO
To import it just add <import class="Name.Space.ProductDTO, Assembly"> right after your hibernate-mapping element. Of course the generating of the DTO's can get much more complex than the samples i have shown. They could span multiple business object requiring complex queries but the concept remains the same.
Okay, so these options are valid only for folks using an LINQ empowered ORM's or frameworks with equivalent functionality to the nHibernate sample above. One thing we could do is to create the DTO's from the fully populated objects. Of course this could be a dangerous decision if you don't already have the objects in the current context and the DTO's require a very little subset of the data, so that's definitely worth noting. That beeing said we could do this in a number of ways all which i can thing of writing myself involves plumbing code. So a couple of days ago I stumbled upon a project called otis a object transformer or Object-to-Object mapper if you prefer that term.
The concept is pretty simple, we can define how one object map to another so if we take our very simple case we can specify a mapping on this form:
<?xml version="1.0" encoding="utf-8" ?>
<otis-mapping xmlns="urn:otis-mapping-1.0">
<class name="Name.Space.ProductDTO, Assembly" source="Name.Space.Product, Assembly" >
<member name="ID" />
<member name="Name" />
</class>
</otis-mapping>
In the above case we have the same names on properties in both classes so its pretty simple, but the possibilities in the mapping is many. You can use expression to combine multiple values to one, projections, exchanging certain values etc. I will certainly have to look into the source code of otis and have a look of its capabilities as the documentation is a bit sparse.
To utilize the above mapping we configure the framework and use a generic class to get Assembler classes that can convert our types, its pretty simple:
Product product = ...; //Our fully populated product instance Otis.Configuration conf = new Otis.Configuration(); //Looks for embedded ressource with *.otis.xml ending conf.AddAssemblyResources(Assembly.GetExecutingAssembly(), "otis.xml"); //Declare our assembler var asm = conf.GetAssembler<ProductDTO, Product>(); //Use the assembler to get the DTO ProductDTO dto = asm.AssembleFrom(product);
As I said I will definitely dive into the source to explore which features are available and how the transformation is done and what the costs of it is. The main issue I have with the approach is that we could do the same using code and to make it more flexible lambda expressions and have it strongly typed and avoid the verbosity of XML, but lets see how feature rich Otis is before dismissing it.
A .NET User Group is starting up in Copenhagen for more information check http://cnug.dk/ (in Danish). I Hope to see many of the Danish developers on the 19th of June in Ballerup. Its gonna be a talk about expectations for the User Group and a presentation of some concepts from object relational mapping.
A .NET User Group is starting up in Copenhagen for more information check http://cnug.dk/ (in Danish). I Hope to see many of the Danish developers on the 19th of June in Ballerup. Its gonna be a talk about expectations for the User Group and a presentation of some concepts from object relational mapping.
A .NET User Group is starting up in Copenhagen for more information check http://cnug.dk/ (in Danish). I Hope to see many of the Danish developers on the 19th of June in Ballerup. Its gonna be a talk about expectations for the User Group and a presentation of some concepts from object relational mapping.
Notice that the scrollbar isn't at the bottom. That's a lot of data to fetch if you only show a single page of them
(click for larger image)
Notice that the scrollbar isn't at the bottom. That's a lot of data to fetch if you only show a single page of them
(click for larger image)
Notice that the scrollbar isn't at the bottom. That's a lot of data to fetch if you only show a single page of them
(click for larger image)
So if you need to generate passwords easy you don't have to reinvent the wheel, you can use functionality that the Mempership functionality from ASP.NET already has. On the Membership class in System.Web.Security namespace is a static method for generating passwords. You can specify a length and how many non alphanumeric characters it should contain.
Of course its not exotic in anyway and you can not control the set of characters used (apart from how many should be non alphanumeric) and it does not generate pronounceable passwords.
string password = Membership.GeneratePassword(7, 1);
The above code will generate a string with seven random characters. Its worth taking note of the second parameter. It specifies the minimum number of non-alphanumerical characters so the generated password can contain more than one in the above case.
If you need to generate pronounceable passwords I would recommend you take a look at the C implementation available here: http://www.multicians.org/thvv/tvvtools.html#gpw it covers the theory behind using trigraphs and furthermore shows implementation of how to extract trigraphs from a dictionary and how to use this to generate the actual passwords.
But to keep it short, if you just need a random set of chars. Use the features already in the framework instead of rolling your own! The lines saved makes fewer lines that could contain that tricky bug you are hunting a few months from now.
So if you need to generate passwords easy you don't have to reinvent the wheel, you can use functionality that the Mempership functionality from ASP.NET already has. On the Membership class in System.Web.Security namespace is a static method for generating passwords. You can specify a length and how many non alphanumeric characters it should contain.
Of course its not exotic in anyway and you can not control the set of characters used (apart from how many should be non alphanumeric) and it does not generate pronounceable passwords.
string password = Membership.GeneratePassword(7, 1);
The above code will generate a string with seven random characters. Its worth taking note of the second parameter. It specifies the minimum number of non-alphanumerical characters so the generated password can contain more than one in the above case.
If you need to generate pronounceable passwords I would recommend you take a look at the C implementation available here: http://www.multicians.org/thvv/tvvtools.html#gpw it covers the theory behind using trigraphs and furthermore shows implementation of how to extract trigraphs from a dictionary and how to use this to generate the actual passwords.
But to keep it short, if you just need a random set of chars. Use the features already in the framework instead of rolling your own! The lines saved makes fewer lines that could contain that tricky bug you are hunting a few months from now.
So if you need to generate passwords easy you don't have to reinvent the wheel, you can use functionality that the Mempership functionality from ASP.NET already has. On the Membership class in System.Web.Security namespace is a static method for generating passwords. You can specify a length and how many non alphanumeric characters it should contain.
Of course its not exotic in anyway and you can not control the set of characters used (apart from how many should be non alphanumeric) and it does not generate pronounceable passwords.
string password = Membership.GeneratePassword(7, 1);
The above code will generate a string with seven random characters. Its worth taking note of the second parameter. It specifies the minimum number of non-alphanumerical characters so the generated password can contain more than one in the above case.
If you need to generate pronounceable passwords I would recommend you take a look at the C implementation available here: http://www.multicians.org/thvv/tvvtools.html#gpw it covers the theory behind using trigraphs and furthermore shows implementation of how to extract trigraphs from a dictionary and how to use this to generate the actual passwords.
But to keep it short, if you just need a random set of chars. Use the features already in the framework instead of rolling your own! The lines saved makes fewer lines that could contain that tricky bug you are hunting a few months from now.
I often get asked question about nHibernate issues the question discussed last in this post is often brought up. But lets start out with a few simple exceptions that can sometimes take up more of your time than you would like.
"NHibernate.MappingException : Unknown entity class: MyNamespace.With.Persistent.Class"
You are trying to use a class as persistent that nHibernate wouldn't know how to handle. The number one reason for this error is that you have mapping files as embedded resources and that you forgot to actually embed the mapping file.
"NHibernate.MappingException : persistent class ClassName not found" or "NHibernate.MappingException : associated class not found: ClassName"
This is usually an error in your mapping, nHibernate can't find the class you reference in your mapping. This is often caused by typos or missing to specify in which assembly or namespace your persistent class is to be found. You can specify a default assembly and namespace in the <hibernate-mapping> element or you can write the name of your classes with the assembly and namespace specified on the form "Namespace.ClassName, Assembly".
"NHibernate.InvalidProxyTypeException : The following types may not be used as proxies"
This is a classic, if you want to use nHibernates lazyloading features you need to specify your classes properties as virtual so nHibernate can create proxies for you. If you don't need to use lazyloading on specific type mark these types with lazy="false" in the class element, and you won't have to mark its properties as virtual.
So that's a handful of the most common exceptions when starting out with nHibernate. Lets move on to a question I have answered quite a few times. People often want to minimize the number of roundtrip's to the database by joining and retrieving larger resultsets and have nHibernate transform this larger set of results into the correct object graph. Whether this is a good optimization depends heavily on the expected data since it could result in a huge amount of redundant data transferred between database and application. But nonetheless the thing that often tricks people is illustrated by the following test:
//Assumme we have 2 invoices with 3 invoicelines each
IList<Invoice> invoices = s.CreateCriteria(typeof (Invoice)).SetFetchMode("InvoiceLines", FetchMode.Join).List<Invoice>();
Assert.AreEqual(2, invoices.Count);
This test will fail, because you actually get 6 invoice entities back. That's because the resultset contains duplicate invoices (one for each InvoiceLine) and nHibernate transforms these into invoice instances. One way to fix this is to specify that you want distinct root entities back. This is done by specifying a result-transformer like this:
IList<Invoice> invoices =
s.CreateCriteria(typeof (Invoice)).
SetFetchMode("InvoiceLines", FetchMode.Join).
SetResultTransformer(CriteriaUtil.DistinctRootEntity).
List<Invoice>();
So what if your data isn't suitable for joining, you might end up with the large resultset I mentioned earlier? And we don't want to hit the N+1 Select problem by selecting the InvoiceLines for each of the fetched Invoice's. That's were nHibernates batch fetching can be used. We have retrieved all the Invoices we want to use and afterwards we want to select the invoicelines for those. We can specify that our InvoiceLines should be retrieved in batches by specifying a batch-size on the collection in our mapping file.
<set name="InvoiceLines" batch-size="20"> <key column="InvoiceID" /> <one-to-many class="InvoiceLine" /> </set>
I just used 20 as an example, this means that nHibernate will fetch the InvoiceLines for 20 Invoices at a time. So this will result in two roundtrip's(in our example case), and this without fetching duplicate data in the resultsets. You could optimize some scenarios like the one above using MultiQuery or MultiCriteria, that is sending multiple queries in one roundtrip, but that's another story.