How to prevent Nhibernate from fetching derived class? - nhibernate

I am using Nhibernate and I have a problem when fetching a base class with multiple derived classes (each class mapping a different table). When I watch the request, Nhibernate joins on every derived tables which has a huge an impact on the performances...
Here is a simplified vision of my classes :
public class Animal{
public virtual int ID { get; set;}
public virtual string Name { get; set;}
}
public class Dog : Animal{
//others properties
}
public class Cat: Animal{
//others properties
}
public class Person{
public virtual int ID { get; set;}
public virtual IEnumerable<Animal> Animals { get; set;}
}
A person has a list of Animals and I just want their names. The example is not perfect and more it's more complicated (a banking program) but it reflect well my problematic.
I KNOW it can be done differently etc, but it is a legacy so I don't have a choice...
Thanks in advance.

IMO NHibernate will only joind tables which contain projected columns. define a query but do not return Person but project into a dto/anonymous class the properties you need

After all, I created a class AnimalBase which is inherited by Dog, Cat and so forth and a class Animal without any child (both having the interface IAnimal).
As in 95% of my request, I only need Animal, I reference this class in my other objects like Person.
Not perfect but I did not find anything better...
Thanks Firo for your help.

Related

Object mapper vs Object wrapper

I would appreciate a little help here...
Lets say that in an application we have a Data Layer and a Business Logic Layer. In the DAL we have the following entity:
public class Customer {
public string Name {get; set;}
public ICollection<Address> Addresses {get; set;}
}
public class Address {
public string Street {get; set;}
}
In the BLL we have the following POCOs:
public class CustomerDto {
public string Name {get; set;}
public ICollection<AddressDto> Addresses {get; set;}
}
public class AddressDto {
public string Street {get; set;}
}
The entities in the DAL are populated with a ligth-weight ORM and retrieve from the BLL using a repository. Ex:
public class CustomerInformationService {
private readonly ICustomerRepository _repository {get; set;}
public CustomerInformationService (ICustomerRepository repository)
{
_repository = repository;
}
public class CustomerDto Get(int id)
{
var customerEntity = _repository.Get(id);
var customerDto = /* SOME TRANSFORMATION HERE */
return customerDTO;
}
}
My questions is about the /* SOME TRANSFORMATION HERE */ part. There is a discussion in our team about how to do the "mapping".
One approach is to use a mapper either an automapper or a manual mapping.
The second approach is to use sort of like a wrapper around Entity and reference the DTO in order to save a copying operation between object. Something like this:
public class CustomerDto
{
private IEntity _customerEntity;
public IEntity CustomerEntity { get {return _customerEntity;}}
public CustomerDto(IEntity customerEntity)
{
_customerEntity = customerEntity;
}
public string Name
{
get { return _customerEntity.Name; }
}
public ICollection<Address> Addresses
{
get { return _customerEntity.Addresses; }
}
}
The second approach feels a little weird to me because _customerEntity.Addresses feels like a leak (_customerEntity's reference) between my DAL and my BLL but I am not sure.
Are there any advantages/disavantages of using one approach over the other one?
Additional info: We usually pull a max. of 1000 records at a time that would need to be transform between Entity and DTO.
You did not mentioned your "ligth-weight ORM". I will answer in two sections.
If you are using ORM that creates proxies
You should avoid exposing Entities outside certain boundary. ORMs like NHibernate/EF implement lazy loading based on proxies. If you expose Entities to application/UI layer, you will have little control over ORM behavior. This may lead to many unexpected issues and debugging will also very difficult.
Wrapping Entities in DTOs will gain nothing. You are accessing Entities anyway.
Using DTOs and mapping them with some mapper tool like AutoMapper is good solution here.
If you are using ORM that does not create proxies
Do NOT use DTOs, directly use your Entities. DTOs are useful and recommended here in many cases. But the example you given in question does not need DTOs at all.
In case you choose to use DTOs, wrapping Entities in DTOs does not make sense. If you want to use Entity anyway, why wrap it? Again, tool like AutoMapper could help.
Refer this question. It's bit different; I am asking Yes/No and you are asking How. But still it will help you.
I bet for the service layer approach. Basically because something that looks like a business object or domain object has nothing to do with DTOs.
And, indeed, you and your team should use AutoMapper instead of repeating the same code tons of times which will consist in setting some properties from A to B, A to C, C to B...

One controller/view for entities with same properties? (DRY code)

We have quite a few lookup entities that all have the same structure - just ID and Name. For example, Gender, Ethnicity are just dropdown lists on a Patient view. Each lookup entity has views for viewing/adding/editing the values. Each entity has its own controller with nearly identical actions - Index (view list), Create, and Edit. The only thing different is the type.
Is there a way to create one controller and one set of views to manage all of these lookup entities using generics, a base entity, some other technique or a combination of these?
One simple thing you can do is create an Interface for ID and Name. Then inherit it in the models that you need to.
Example
public interface IEntity
{
int Id { get; set; }
string Name { get; set; }
}
Inherit this in your models
public class Gender : IEntity
{
}

Mapping to a different view based on child type

So i have a situation where i have common base type but i need to map to a different view based on the child type.
It looks like i can use a generic mapping class to handle the inheritance
http://geekswithblogs.net/nharrison/archive/2010/07/09/inheriting-a-class-map-in-fluent-nhibernate.aspx
But how can i conditionally map to a different view based on the child type? I see an EntityType property but it says its obsolete and will be made private in the next version.
As an example i have a base class of ContactInfo is standard between contact types but the values come from different places depending on the contact type, this I'll handle through the sql view.
using any mapping the referenced entity comes from a different table
class ContactInfo
{
public virtual long Id { get; set; }
public virtual ContactDetails Details { get; set; }
}
public ContactInfoMap
{
...
ReferencesAny(x => x.Details)
.EntityIdentifierColumn("details_id")
.EntityTypeColumn("contactType")
.IdentityType<long>()
.AddMetaValue<FooContactDetails>("1")
.AddMetaValue<BarContactDetails>("4");
}

Invalid index n for this SqlParameterCollection with Count=m

I'm getting this nasty error in Castle Active Record (wrapped around NHibernate) when I try to save a class:
Invalid index n for this SqlParameterCollection with Count=m
I know that this error is caused by a property being mapped multiple times in a class however I'm not sure how to get around it. I have two child classes that both map back to the class in question using the same column (IpAddressNumber). Also IpAddressNumber is the primary key of the class, which results in NHibernate trying to map the IpAddressNumber property three times (just a guess.)
Here is the class:
[ActiveRecord(Lazy=true)]
public class DeviceConfiguration : UsersDatabase<DeviceConfiguration>
{
[PrimaryKey]
public virtual long IPAddressNumber { get; set; }
[BelongsTo("IPAddressNumber", Lazy = FetchWhen.OnInvoke)]
public virtual Vehicle Vehicle { get; set; }
[BelongsTo("IPAddressNumber", Lazy = FetchWhen.OnInvoke)]
public virtual JBusConfiguration JBusConfiguration { get; set; }
}
Any help would be greatly appreciated...
I ended up having to just remove the second association altogether to get around this issue. Not a great solution but the only one I could find.

Fluent NHibernate & one-to-one

For a (very) long time I've been looking for an example on how to correctly implement a one-to-one mapping with Fluent NHibernate.
Most resources I find say:
I think you mean a many-to-one
However no one actually gives an example on how to correctly implement the one-to-one relation.
So, could you give an one-to-one mapping example with Fluent NHibernate?
Note: I'm not interested in people saying "what's your model, you might actually need HasMany". No, thanks, I simply need a one-to-one example.
To be more precise, I know the syntax. That's the only thing I could find by searching by myself. What I'm looking for is a more complete example, including a ((very) simple) database setup, and the whole mapping, of all entities that participate in the relationship, which I think would have reasonable size for Stack Overflow.
I've solved my problem.
I've also written a somewhat detailed article on this problem, that you can find at: http://brunoreis.com/tech/fluent-nhibernate-hasone-how-implement-one-to-one-relationship/index.html
You will find a scenario in which we want a one-to-one relationship, the database schema as we would like it, the code of the model as it needs to be to meet NHibernate requirements, and the Fluent mapping that corresponds to the situation.
these are the two classes.
public class A
{
public virtual int Id {get;set;}
public virtual string P1 {get;set;}
public virtual string P2 {get;set;}
public virtual string P3 {get;set;}
public virtual B child { get; set; }
}
public class B
{
public virtual int Id {get;set;}
public virtual string P4 {get;set;}
public virtual string P5 {get;set;}
public virtual string P6 {get;set;}
public virtual A parent;
}
this should be added in the fluent configuration.
public AMap()
{
/* mapping for id and properties here */
HasOne(x => x.child)
.Cascade.All();
}
public BMap()
{
/* mapping for id and properties here */
References(x => x.parent)
.Unique();
}
This is the best example I've seen. Hopefully it meets your needs.
HasOne(x => x.Prop)