Free Nhibernate Classes and Column Order

Our objects have a group of common properties. To reduce duplicate mapping, I created a base ClassMap that displays identifiers and general properties. For each ClassMap object, I just subclass the database, and it works great. For a new project, we also let NH generate a DB schema for us. The problem is that the order of the columns is such that the properties from the base ClassMap class first appear, followed by everything that appears in the subclass. The requirement for this assembly is that the columns are displayed in a specific order.

To get around this, I did the following.

public class BaseMap<T> : ClassMap<T> where T : Entity { public BaseMap() { Id(x => x.Id); MapEntity(); Map(x => x.CommonProperty1); Map(x => x.CommonProperty2); Map(x => x.CommonProperty3); } protected virtual void MapEntity() { } } public class SomeEntityMap : BaseMap<SomeEntity> { public SomeEntity() { base.MapEntity(); } protected override void MapEntity() { Map(x => x.SomeEntityProperty1); Map(x => x.SomeEntityProperty2); Map(x => x.SomeEntityProperty3); } } 

It works, but it feels like a hack. Besides the hacking factor, is there anything here that might be problematic?

+4
source share
2 answers

If you made a base class and an abstract map method, it would feel less hacked ...

 public abstract class BaseMap<T> : ClassMap<T> where T : Entity { public BaseMap() { Id(x => x.Id); MapEntity(); Map(x => x.CommonProperty1); Map(x => x.CommonProperty2); Map(x => x.CommonProperty3); } protected abstract void MapEntity(); } public class SomeEntityMap : BaseMap<SomeEntity> { protected override void MapEntity() { Map(x => x.SomeEntityProperty1); Map(x => x.SomeEntityProperty2); Map(x => x.SomeEntityProperty3); } } 

This will keep the columns of common properties at the end of the table. Keep in mind that after that foreign key columns will be added. I don’t think there is any way to have full control over the order of the columns unless you manually modify the schema creation scripts.

+5
source

I just needed to implement something similar to myself.

Assuming you have

 public class SomeEntity : Entity { ... } 

Less hacked way:

 public abstract class BaseMap<T> : ClassMap<T> where T : Entity { public BaseMap() { Id(x => x.Id); Map(x => x.CommonProperty1); Map(x => x.CommonProperty2); Map(x => x.CommonProperty3); } } public class SomeEntityMap : BaseMap<SomeEntity> { public SomeEntity() { Map(x => x.SomeEntityProperty1); Map(x => x.SomeEntityProperty2); Map(x => x.SomeEntityProperty3); } } 

The same result at the end, but you do not use overridden methods to add mappings. This will be taken into account automatically.

+3
source

All Articles