Is there a clean way to mix fluent mappings with automappings? Ideally, I'd like to say "if I don't have a ClassMap for a domain object, then automap it". Is there a recommended approach? I'd rather not use attributes on my business objects that are data access related (ex: [UseAutoMapping]).
Yes - check out IAutoMappingOverride
Basically, any mappings which override the Automapping behaviour need to implement this interface.
e.g.
public class MyClassMap : IAutoMappingOverride<MyClass>
{
public void Override(AutoMapping<MyClass> mapping)
{
mapping.IgnoreProperty(host => host.HostName);
mapping.Table("BobsHardware");
}
}
Related
I'm having an issue with Fluent NHibernate AutoPersistenceModelGenerator. It doesn't want to pick up custom maps.
Using Sharp Architecture 2.0, Fluent NHibernate 1.2 and NHibernate 3.1.
My current relevant configuration is as follows:
public AutoPersistenceModel Generate()
{
// This mappings group works with the exception of custom maps!!
var mappings = AutoMap.AssemblyOf<SecurableEntity>(new AutomappingConfiguration());
mappings.Conventions.Setup(GetConventions());
mappings.IgnoreBase<Entity>();
mappings.IgnoreBase<SecurableEntity>();
mappings.IgnoreBase(typeof(EntityWithTypedId<>));
mappings.UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();
//mappings.UseOverridesFromAssemblyOf<UserMap>(); // Should call Override method of UserMap, but doesn't appear to...
mappings.Override<User>(new UserMap().Override()); // This hack fixes the issue with calling the Override method of UserMap.
mappings.UseOverridesFromAssemblyOf<UserMap>();
return mappings;
}
class UserMap : IAutoMappingOverride<User>
{
public void Override(AutoMapping<User> mapping)
{
//mapping => mapping.Table("Users");
mapping.Table("Users");
}
public Action<AutoMapping<User>> Override()
{
return map =>
{
map.Table("Users");
};
}
}
I've tried making various modifications to the configuration and pouring over internet articles on Fluent NHibernate, to no avail. I have a working version using Sharp Arch 1.x, and earlier versions of NHibernate and Fluent. I'm assuming that there has been a change in syntax that I'm missing. Any and all help would be greatly appreciated.
Thank you!
John
Fluent NHibernate use Assembly.GetExportedTypes() method to get all the overrides from given assembly. As this method's documentation say, it gets the public types defined in this assembly that are visible outside the assembly. Your override is implicitly internal. Just add public before class UserMap and it'll work.
I have a convention for my ids, which automatically maps properties with a name of Id as the identifier. As requirements are being fleshed out I need to tweak a domain model so naturally I went online and found that I need to create a class that inherits from IAutoMappingOverride<T>.
My convention:
public class PrimaryKeyConvention : IIdConvention, IIdConventionAcceptance
{
public void Apply(IIdentityInstance instance)
{
instance.Column("Id");
instance.GeneratedBy.SeqHiLo(instance.Name, "10");
}
public void Accept(IAcceptanceCriteria<IIdentityInspector> criteria)
{
criteria.Expect(x => x.Generator, Is.Not.Set);
}
}
My override:
public class LocateMappingOverride : IAutoMappingOverride<Locate>
{
public void Override(AutoMapping<Locate> mapping)
{
mapping.Map(x => x.SendTo).Not.Nullable();
}
}
The convention does work as expected if I remove my override.
The exception I get is The entity 'LocateMappingOverride' doesn't have an Id mapped. Use the Id method to map your identity property. For example: Id(x => x.Id)..
Is it possible to use conventions in conjunction with mapping overrides?
The answer is - yes, automapping can work with overrides.
Look what the error said. The problem is not with Locate entity, but with LocateMappingOverride entity, and that class should not be treated as entity, of course. You must have IAutomappingConfiguration configured so that FluentNHibernate's rule what to treat as entity includes LocateMappingOverride, too. And it does not have an Id mapped, indeed.
You should either:
change your IAutomappingConfiguration so that classes that implements IAutoMappingOverride<> are excluded
move the override outside the scope that is searched for entities
or introduce a common marker interface that all entities need to implement, i.e. IEntity and change IAutomappingConfiguration rules respectively.
I have the following IIdConvention for a FluentNHibernate automapping. I want all of my id properties to use a custom type that is represented by a string property but the CustomType is never applied to my mappings.
public class PrimaryKeyHasTableName : FluentNHibernate.Conventions.IIdConvention
{
public void Apply(FluentNHibernate.Conventions.Instances.IIdentityInstance instance)
{
instance.Column(instance.EntityType.Name + "Id");
instance.CustomType<CustomIdType>();
}
}
When I looked into the FluentNHibernate source it appears that the Type for the id property has already been set so it is not being set by my convention.
If I use a ClassMap to map the class manually I have not problem setting the CustomType for the Identity property.
Id(x => x.Id)
.Column("UserId")
.CustomType<OnFileIdType>();
Does anybody know how I can successfully set the custom id property using a convention?
Or get my convention to run earlier in the mapping process so that the Type isn't already set by the time my code runs.
Also, here's my configuration code:
Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(connString))
.Mappings(m =>
{
m.FluentMappings.AddFromAssemblyOf<BaseEntity>();
m.AutoMappings.Add(AutoMap.AssemblyOf<BaseEntity>()
.Where(t => t.Namespace.EndsWith("Models.Domain"))
.Conventions.AddFromAssemblyOf<BaseEntity>()
.UseOverridesFromAssemblyOf<BaseEntity>()
);
})
.ExposeConfiguration(CreateSchema)
.BuildSessionFactory();
Thanks.
I don't think you can achieve what you want with conventions.
One thing you can try is having all your entities subclass from an abstract entity that defines the Id property and has the custom type mapping for it.
I wouldn't recommend this however, It will just open room for more automapping problems.
Just go for the manual CustomType for each class map.
I'm having the exact same problem, it would be great if FNH's IIdConvention supported this.
After trying a few things and reading this I have resigned myself to implementing IAutoMappingOverride for entities using a custom type for their Id.
public class ProductMap : IAutoMappingOverride<Product>
{
public void Override(AutoMapping<Product> mapping)
{
mapping.Id(x => x.Id).CustomType<ProductId>();
}
}
Using automapping override instead of ClassMap will continue to automap the rest of your properties. Alter your AutoMappings initialisation code to include
.Overrides.AddFromAssemblyOf<BaseEntity>()
I am getting the same problem. I believe that it is arising from the invocation of Conventions.AddFromAssemblyOf<BaseEntity>(), which is causing your custom convention to not be applied.
(By the way, the posted code will work only if your convention classes are in the same assembly as your BaseEntity - it might be safer to use Conventions.AddFromAssemblyOf<PrimaryKeyHasTableName>())
A bug was raised about AddFromAssemblyOf back in February 2011: Fluent NHibernate - Setting CutomType IIdConvention. There is no resolution posted.
The work-around appears to be to add each of the Conventions explicitly
Conventions.Add<PrimaryKeyHasTableName>()
To check this, you can add the following line after the line which adds the automappings, in order to export the mappings to an hbm.xml file on your hard drive, and take a look at the generated mappings.
m.AutoMappings.ExportTo(#"C:\ExportedMappings")
Also, I suggest you add a breakpoint into the Apply method and run the code to ensure that it is being invoked.)
I am retrofitting a very large application to use NHibernate as it's data access strategy. Everything is going well with AutoMapping. Luckily when the domain layer was built, we used a code generator. The main issue that I am running into now is that every collection is hidden behind a custom class that derives from List<>. For example
public class League
{
public OwnerList owners {get;set;}
}
public class OwnerList : AppList<Owner> { }
public class AppList<T> : List<T> { }
What kind of Convention do I have to write to get this done?
I don't think you're going to be able to achieve this with a convention. You will have to create an auto mapping override and then do the following:
mapping.HasMany(l => a.owners).CollectionType<OwnerList>();
NHibernate seems to support a special case of one to one mapping (That doesn't require a 1-m mapping on each side of the relationship).
See this article by Ayende:
http://nhibernate.info/blog/2009/04/18/nhibernate-mapping-lt-one-to-one-gt.html
I have no idea how to specify this in Fluent NHibernate though - is this possible?
Ah, just found from a helpful person in the Fluent group that I can use
HasOne(x => x.Cover);
Missed it somehow before :/
One scenario is with subclasses. You can specific a table per hierarchy or per class.
You would need to override for the per hierarchy something like below:
public class UserMap : IAutoMappingOverride<User>
{
public void Override(AutoMapping<User> mapping)
{
mapping.DiscriminateSubClassesOnColumn<int>("UserType");
}
}
public void Override(AutoMapping<Person> mapping)
{
mapping.Table("Persons");
DiscriminatorValue((int)UserTypes.Person);
}