Fluent mapping - entities and classmaps in different assemblies - nhibernate

When using fluent configuration to specify fluent mappings like this:
.Mappings(m => m.FluentMappings.AddFromAssembly(typeof(UserMapping).Assembly))
At the moment I am getting a "NHibernate.MappingException : No persister for" error.
Is it a problem that my Entities and my ClassMaps are in different assemblies? Presumably AddFromAssembly is interested in the assembly that holds the class maps, not the entities? (that is what I have assumed)
Thanks!
UPDATE:
Sorry for not responding to answers very quickly - I had to travel unexpectedly after setting the bounty.
Anyway, thanks for the responses. I've taken a look through them and have updated my code to use AddFromAssemblyOf rather than AddFromAssembly, but still am getting the same error. Possibly I am doing something stupid. Here is the full code for the session factory code I am using:
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var mysqlConfig = FluentNHibernate.Cfg.Db.MySQLConfiguration
.Standard
.ConnectionString("CONNECTION STRING OMITTED")
.UseOuterJoin()
.ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
_sessionFactory = FluentNHibernate.Cfg.Fluently.Configure()
.Database(mysqlConfig)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<User>())
.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
I receive this exception when trying to run a test in nunit that makes use of a repository using this session mechanism:
NHibernate.MappingException : No persister for: xxxx.Model.Entities.User
Thanks
P.S.:
I've tried using both and in AddFromAssemblyOf();
Project with mapping definitions (DataAccess) has reference to project with entities (Model).

What version of Fluent NHibernate are you using? There have been problems with the release candidate and the 1.0 release versions. You may want to consider downloading the latest version from the SVN repository.
http://fluent-nhibernate.googlecode.com/svn/trunk/
Additionally, you may want to check the connection string to make sure that it is completely correct, and you want to make sure that "User" below points to a class.
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<User>())
Also, I should mention that when you use AddFromAssemblyOf, fluent will try to map EVERY class in that assembly. If you have any other classes in that namespace you will want to filter them. There are several different ways to accomplish this. The simplest way is to just place all of the POCOs you want to map in their own namespace and then do something like the following.
.Mappings(m => m.AutoMappings
.Add(AutoMap.AssemblyOf<MyNamespace.Entities.MyClass>()
.Where(type => type.Namespace == "MyNamespace.Entities")
The Where clause will filter items you don't want mapped.

Is it a problem that my Entities and my ClassMaps are in different assemblies?
No there is nothing wrong with that as long as you ClassMap project have refrerence to your Entities project
anyway try this :
m.FluentMappings.AddFromAssemblyOf<UserMapping>()
if this doesn't work post the entire error

Certainly having your entities in a different assembly should not cause a problem as Yassir alludes to above.
According to the Fluent NHibernate Wiki the AddFromAssemblyOf method infers or reflects on the Assembly that contains all of your entities and will map to them when you supply any entity name to it. From the documentation on the FNH wiki you would construct the method as follows:
m.FluentMappings
.AddFromAssemblyOf<YourEntity>();
Therefore in your example, if the entity you are mapping is named User then your code should be constructed as follows:
m.FluentMappings
.AddFromAssemblyOf<User>();
Hope this is of help.

has this been solved? if not could you inlcude your setup?
for example here is my example one
public static ISessionFactory GetSessionFactory()
{
//Old way, uses HBM files only
//return (new Configuration()).Configure().BuildSessionFactory(); //requies the XMl file.
//get database settings.
Configuration cfg = new Configuration();//.Configure();
ft = Fluently.Configure(cfg);
//DbConnection by fluent
ft.Database
(
MsSqlConfiguration
.MsSql2005
.ConnectionString(c => c
.Server(".\\SqlExpress")
.Database("NhibTest")
.TrustedConnection()
)
.ShowSql()
.UseReflectionOptimizer()
);
//set up the proxy engine
//cfg.Properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
//get mapping files.
ft.Mappings(m =>
{
//set up the mapping locations
m.FluentMappings.AddFromAssemblyOf<PersonMap>();//.ExportTo("C:\\mappingfiles");
//m.Apply(cfg);
});
//return the SessionFactory
return ft.BuildSessionFactory();
}
the project structure is as follows
project.Data <- mapping files, and Dao's (also hibernate session manager, containing the above code)
project.Core <- POCO's
project.UI
also have look here incase you have a mixture of Fluent NHibernate and NHibernate configuration
Finally have a look at S#arp Architectures way, as i think it includes this mixture
NhibernateSession <- function : private static ISessionFactory CreateSessionFactoryFor
Hope this helps

Related

Fluent NHibernate does not call my ClassMap<ControlEntity> class

I use NHibernate for a dynamic website that its modules can be loaded dynamically, so when I want to build a sessionFactory, I use a way to find all assemblies and sort them with their dependencies
after all, I add them to Configuration instance I created and it works.
Now I want to change configuration type from hbm.xml files to fluent
I added below codes:
sessionFactory =
Fluently
.Configure()
.Database(
FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromAppSetting("connectionString")
)
)
.Mappings(
m => m.AutoMappings.Add(
AutoMap.Assemblies(
new FarayanConfig(),
assembliesArray
)
)
).BuildSessionFactory();
FarayanConfig is:
class FarayanConfig : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
return type.Name.EndsWith("Entity");
}
public override bool IsVersion(FluentNHibernate.Member member)
{
return member.Name == "Version";
}
}
also I have a class in an assembly that will be loaded by this code (notice that assembly is not referenced, will be loaded dynamically) with a class named ControlEntity and also another class:
public class ControlEntityMap : ClassMap<ControlEntity>
{
public ControlEntityMap()
{
HasMany(x => x.Properties).Component(c => {
c.Map(v => v.Culture);
c.Map(v => v.Name);
c.Map(v => v.Value);
});
}
}
now the problem is constructor of ControlEntityMap will not execute!
what I must do?
Because of you are trying to use AutoMap.
You can use something like this:
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("your assembly name")))
Update:
You are doing right by ovverride DefaultAutomappingConfiguration for this situation but also you are trying to AutoMap all classes which ones end with "Entity" and your class which one you want to ignore it from AutoMap also ends with "Entity". I think you can seperate your classes in different namespaces and declare it in your ShouldMap property.
And there are some information in FluentNhibenate Wiki:
You can ignore base types by simply excluding them from your
ShouldMap(Type) method, that's sometimes the cleanest option; however,
if you want to be a bit more explicit you can use the IgnoreBase
method.
After AutoMap.AssemblyOf() we need to alter the conventions
that the auto mapper is using so it can identify our base-class.
AutoMap.AssemblyOf(cfg) .IgnoreBase();
We've added the IgnoreBase call which simply instructs the
automapper to ignore the Entity class; you can chain this call as many
times as needed.

Custom Fluent NHibernate maps not working with AutoMapping

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.

How to add mappings by namespace in Fluent NHibernate

In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.
The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
.Mappings(m => m.FluentMappings.Add<UserClassMap>()
If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?
It's odd that FluentNHibernate supports this type of filtering for automapping, but not for ClassMaps. It shouldn't be too hard to add this feature yourself, though, via the magic of extension methods. Try this:
public static FluentMappingsContainer AddFromAssemblyOf<T>(
this FluentMappingsContainer mappings,
Predicate<Type> where)
{
if (where == null)
return mappings.AddFromAssemblyOf<T>();
var mappingClasses = typeof(T).Assembly.GetExportedTypes()
.Where(x => (typeof(IMappingProvider).IsAssignableFrom(x)
|| typeof(IExternalComponentMappingProvider).IsAssignableFrom(x))
&& where(x));
foreach (var type in mappingClasses)
{
mappings.Add(type);
}
return mappings;
}
... and use it like this:
m.FluentMappings.AddFromAssemblyOf<UserClassMap>(t => t.Namespace.StartsWith("One.Of.The.Two.Namespaces"));
I wound up writing an extension method that does this for me. Basically it uses reflection to iterate over all the types I'm interested in, and add them one-by-one. It is based on the implementation of AddFromAssemblyOf. Usage:
.Mappings(m => m.FluentMappings.AddFromNamespaceOf<UserClassMap>())
Implementation:
public static class FluentNHibernateExtensions
{
public static FluentMappingsContainer AddFromNamespaceOf<T>(
this FluentMappingsContainer fmc)
{
string ns = typeof(T).Namespace;
IEnumerable<Type> types = typeof(T).Assembly.GetExportedTypes()
.Where(t => t.Namespace == ns)
.Where(x => IsMappingOf<IMappingProvider>(x) ||
IsMappingOf<IIndeterminateSubclassMappingProvider>(x) ||
IsMappingOf<IExternalComponentMappingProvider>(x) ||
IsMappingOf<IFilterDefinition>(x));
foreach(Type t in types) {
fmc.Add(t);
}
return fmc;
}
/// <summary>
/// Private helper method cribbed from FNH source (PersistenModel.cs:151)
/// </summary>
private static bool IsMappingOf<T>(Type type)
{
return !type.IsGenericType && typeof(T).IsAssignableFrom(type);
}
}
Caveats:
The name is a little misleading, since it only searches one assembly. It should perhaps be called AddFromAssemblyAndNamespaceOf, but that's a little verbose.
It is not entirely future-proof. If future versions of FNH add or remove some of the mappable interfaces, it wouldn't include them.
But it works for my purposes.
... AutoMap.AssemblyOf<Person>().Where(x => x.Namespace.EndsWith("Domain")) ...
There is no way to do this. I recommend separating the namespaces out into separate projects. Remember:
Separate namespaces, same project when logical separation makes sense.
Separate namespaces, separate projects when physical separation makes sense.
In this case, since you can't separate by namespace in nhibernate mappings, physical separation makes sense. You can, however, get around this with with fluent automaps that use a .Where or a ShouldMap configuration. Look up fluent automaps and see if that can get you where you want to be.

automapping Entities in nhibernate

hii i am having a little problem in mapping all the entities in contained in the namespace "nhibernateTest.Domain" . it basically contains all the Map Classes like , StudentMap, DepartmentMap etc. .. now in case of normal nhibernate what we used to do is :
private ISessionFactory _sessionFactory;
private Configuration _configuration;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
_configuration = new Configuration().Configure().AddAssembly("nHibernateTest");
_sessionFactory = _configuration.BuildSessionFactory();
}
now what it used to do is . look for all the "*.hbm.xml" files in my namespace and automatically map them...
can someone tell me how to do the same for fluent nHibernate ? so that it looks for all map classes and automatically map them so that i dont have to create the session separately for diffrent Map classes ?
You would need to specify your mappings when configuring Fluent NHibernate in your application. This is typically done by
Fluently.Configure()
.Database(/* your database settings */)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<StudentMap>())
.ExposeConfiguration(/* alter Configuration */) // optional
.BuildSessionFactory();
The code above is from this excellent link which talks about how to configure Fluent.

Fluent NHibernate - Setting CutomType IIdConvention

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.)