Fluent NHibernate With Dynamic Table Name - nhibernate

how can I map a dynamic table name to a entity?
Ex, I can have many tables, all have the same structure, however, has its different name, how can I map this using Fluent NHibernate?
remembering that before compiling I do not know the name of these tables.
Can anyone help me?

What you'll probably need to do is put a place holder in the fluent nhibernate mapping for the table name and then replace it after you build the mappings.
Take a look at the following article and I think the first code sample will give you an idea of what you need to do.
http://ayende.com/blog/3294/dynamic-mapping-with-nhibernate
I was able to do this. Here is a rough example:
var fluentConfiguration = Fluently.Configure(NHibernate.Cfg.Configuration().Configure())
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<OrderMap>()
.Conventions.AddFromAssemblyOf<PascalCaseColumnNameConvention>())
.ProxyFactoryFactory("NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate");
var config = fluentConfiguration.BuildConfiguration();
foreach(PersistentClass persistentClass in config.ClassMappings)
{
if(persistentClass.MappedClass == typeof(Order))
{
persistentClass.Table.Name = "Dynamic Table";
}
}
//You could substitute above for each loop with linq unless you have a bunch to replace then use foreach
//config.ClassMappings.First(x => x.MappedClass == typeof(Order)).Table.Name = "Dynamic Table";
var sessionFactory = config.BuildSessionFactory();
using(ISession session = sessionFactory.OpenSession())
{
Order order = session.Query<Order>().FirstOrDefault();
}

Related

Nhibernate: Map column that may not exist in database

Is there a way to map a column that may or may not exist in database or to map it dynamically to a column?
You can dynamically change the mappings but I don't think there is a way to map a column that may or may not exist. The below example is how you might do it if you were using fluent nhibernate.
var fluentConfiguration = Fluently.Configure(NHibernate.Cfg.Configuration().Configure())
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<OrderMap>()
.Conventions.AddFromAssemblyOf<PascalCaseColumnNameConvention>())
.ProxyFactoryFactory("NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate");
var config = fluentConfiguration.BuildConfiguration();
foreach(PersistentClass persistentClass in config.ClassMappings)
{
//Check to see if there are any missing columns from this mapping.
//If so remove the column from the mapping.
//TODO: Query the database and catch errors related to missing columns
// If a column is missing remove it
}
var sessionFactory = config.BuildSessionFactory();

How to get a single value from db using Fluent Hibernate

I'm new to Fluent Hibernate And I'm stuck with a problem I want to get the email id of a user by using his user name means I want to implement the following code using fluent Hibernate
Select emailId from Table where username="User"
I tried the following code but its not give me what i want
public string ForgetPassword(string user)
{
var factory = CreateSessionFactory();
using (var session = factory.OpenSession())
{
var getEmail = session.Query<ClsAccountBL>()
Select(u => u.Email).Where(u => u.User == user).ToString();
return getMail;
}
}
Please help me to solve this
Instead of .ToString() use FirstOrDefault(). The LINQ does not return "single" element.

NHibernate Search N+1 Issue

I'm using NHibernate Search for NHibernate 3.0 GA.
I have this code in my product repository:
public IList<Product> Find(string term)
{
var productFields = new[] { "Name", "Description" };
var importance = new Dictionary<String, float>(2) { { "Name", 4 }, { "Description", 1 } };
var analyzer = new StandardAnalyzer();
var parser = new MultiFieldQueryParser(
productFields,
analyzer,
importance);
var query = parser.Parse(term);
var session = Search.CreateFullTextSession(NHibernateSession.Current);
var tx = session.BeginTransaction();
var fullTextQuery = session.CreateFullTextQuery(query);
fullTextQuery.SetFirstResult(0).SetMaxResults(20);
var results = fullTextQuery.List<Product>();
tx.Commit();
return results;
}
In NH Profiler, I can see that a select statement is issued for every product found. What am I missing?
I found this thread from 2009 but presumably this bug has been fixed.
EDIT [06/06/2011]:
My property mappings as far as associations go are as follows:
mapping.HasManyToMany(c => c.Categories)
.Table("CatalogHierarchy")
.ParentKeyColumn("child_oid")
.ChildKeyColumn("oid")
.Cascade.None()
.Inverse()
.LazyLoad()
.AsSet();
mapping.HasMany(c => c.Variants)
.Table("CatalogProducts")
.Where("i_ClassType=2")
.KeyColumn("ParentOID")
.Cascade.SaveUpdate()
.AsSet();
I don't really want to eager fetch all categories.
As NHibernate.Search is unstable, I would use (and I did) Lucene.NET directly from my application - just to ask Lucene for objects' Ids and then load it using Session.Load().
Also you could change LazyLoad settings at class mapping level, not at relationship level.
Hope it helps.
EDIT: you could specify batch-size for relationships, so they wouldn't cause select N+1 problem
Are you referencing any lazy loaded properties in the product list that is returned by this method? If so, you can change the property mapping to "eager fetch".
I solved this in the end. I realised I had not wrapped the whole thing into a transaction. Once I did, the N+1 issue was gone.
Schoolboy error, but hey, you learn by your mistakes.

Custom naming conventions in Fluent NHibernate AutoMapping

according to this Post it is possible to change the naming convention from "[TableName]_id" to "[TableName]ID". However when I saw the code, I wasn't able to do it with my rather new (about 6 weeks old) version of Fluent NHibernate.
Original code:
var cfg = new Configuration().Configure();
var persistenceModel = new PersistenceModel();
persistenceModel.addMappingsFromAssembly(Assembly.Load("Examinetics.NHibernate.Data"));
persistenceModel.Conventions.GetForeignKeyNameOfParent = type => type.Name + "ID";
persistenceModel.Configure(cfg);
factory = cfg.BuildSessionFactory();
I came up with this:
PersistenceModel model = new PersistenceModel();
model.AddMappingsFromAssembly(assemblyType.Assembly);
model.ConventionFinder.Add(
ConventionBuilder.Reference.Always(part
=> part.ColumnName(part.EntityType.Name + part.Property.Name)));
configuration.ExposeConfiguration(model.Configure);
return configuration.BuildConfiguration();
but this gives me the original Table, because EntityType is not the referenced Entity and I see no property to get the "parent" entity.
How can I do this?
See The answer about removing underscores in Ids using Fluent NHibernate Automapping conventions here.
A portion of the text, the tables and classes are in the link.
Solution:
Add a convention, it can be system wide, or more restricted.
ForeignKey.EndsWith("Id")
Code example:
var cfg = new StoreConfiguration();
var sessionFactory = Fluently.Configure()
.Database(/* database config */)
.Mappings(m =>
m.AutoMappings.Add(
AutoMap.AssemblyOf<Product>(cfg)
.Conventions.Setup(c =>
{
c.Add(ForeignKey.EndsWith("Id"));
}
)
.BuildSessionFactory();
Now it will automap the ShelfId column to the Shelf property in Product.

Combine Fluent and XML mapping for NHibnernate

I just fell in love with NHibernate and the fluent interface. The latter enables very nice mappings with refactoring support (no more need for xml files).
But nobody is perfect, so I am missing the many-to-any mapping in fluent. Does anybody know if it is already there? If so, a simple line of code would be nice.
But to stick to the header of the question, is there any way to combine fluent and normal NHibernate mapping.
Currently I use the following lines for my test setup WITH fluent, and the second code block for my test WITHOUT fluent (with XML mappings). How can I tell fluent to use fluent IF AVAILABLE and XML otherwise...
var cfg = new Configuration();
cfg.AddProperties(MsSqlConfiguration.MsSql2005.ConnectionString.Is(_testConnectionstring).ToProperties());
cfg.AddMappingsFromAssembly(typeof(CatMap).Assembly);
new SchemaExport(cfg).Create(true, true);
var persistenceModel = new PersistenceModel();
persistenceModel.addMappingsFromAssembly(typeof(CatMap).Assembly);
IDictionary<string, string> properties = MsSqlConfiguration.MsSql2005.UseOuterJoin().ShowSql().ConnectionString.Is(_testConnectionstring).ToProperties();
properties.Add("command_timeout", "340");
session = new SessionSource(properties, persistenceModel).CreateSession();
Without Fluent...
config = new Configuration();
IDictionary props = new Hashtable();
props["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
props["dialect"] = "NHibernate.Dialect.MsSql2005Dialect";
props["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
props["connection.connection_string"] = "Server=localhost;initial catalog=Debug;Integrated Security=SSPI";
props["show_sql"] = "true";
foreach (DictionaryEntry de in props)
{
config.SetProperty(de.Key.ToString(), de.Value.ToString());
}
config.AddAssembly(typeof(CatMap).Assembly);
SchemaExport se = new SchemaExport(config);
se.Create(true, true);
factory = config.BuildSessionFactory();
session = factory.OpenSession();
That's it...
Chris
PS: I really like this site, the GUI is perfect, and the quality of all articles is incredible. I think it will be huge :-) Have to register...
ManyToAny's currently aren't implemented (as of time of writing).
Regarding your setup for fluent and non-fluent mappings, you're almost there with your first example.
var cfg = MsSqlConfiguration.MsSql2005
.ConnectionString.Is(_testConnectionstring)
.ConfigureProperties(new Configuration());
cfg.AddMappingsFromAssembly(typeof(CatMap).Assembly); // loads hbm.xml files
var model = new PersistenceModel();
model.addMappingsFromAssembly(typeof(CatMap).Assembly); // loads fluent mappings
mode.Configure(cfg);
new SchemaExport(cfg).Create(true, true);
The main difference is that the SchemaExport is last. I assume your first example was actually loading the fluent mappings, but it'd already created the schema by that point.
You can do exactly what you want to do entirely within Fluent NHibernate.
The following code will use Fluent NHibernate syntax to fluently configure a session factory that looks for HBM (xml) mapping files, fluent mappings, and conventions from multiple possible assemblies.
var _mappingAssemblies = new Assembly[] { typeof(CatMap).Assembly };
var _autoPersistenceModel = CreateAutoPersistenceModel();
Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(_testConnectionstring))
.Mappings(m =>
{
foreach (var assembly in _mappingAssemblies)
{
m.HbmMappings.AddFromAssembly(assembly);
m.FluentMappings.AddFromAssembly(assembly)
.Conventions.AddAssembly(assembly);
}
m.AutoMappings.Add(_autoPersistenceModel );
})
.ExposeConfiguration(c => c.SetProperty("command_timeout", "340"))
.BuildSessionFactory();
There are many other options available to you as well: Fluent NHibernate Database Configuration
Mapping from Foo to Baa:
HasManyToMany< Baa > ( x => Baas )
.AsBag ( ) //can also be .AsSet()
.WithTableName ( "foobar" )
.WithParentKeyColumn ( "fooId" )
.WithChildKeyColumn ( "barId" ) ;
Check out the examples in ClassMapXmlCreationTester - they also show what the default column names are.