Disabling caching in Fluent Nhibernate for a specific override - fluent-nhibernate

We're using convention based mapping with Fluent NHibernate. The mapping looks like so:
.Conventions.Add
(
Table.Is(x => string.Concat(x.EntityType.Name.ToLower(), "s")),
PrimaryKey.Name.Is(x => "Id"),
DefaultLazy.Always(),
DefaultCascade.SaveUpdate(),
AutoImport.Never(),
Cache.Is(x => x.ReadWrite())
)
For most of our objects this is perfect but on certain objects I wish to disable the 2nd level cache. However it doesn't appear that I can do this. There is no fluent option for Cache.None. I've even tried Not.Cache() but that didn't work either.
Has anyone got any ideas on how I can disable the cache for certain selected model objects?

Ok, I managed to find it after some digging around jogged an idea:
Remove the shortcut Cache.Is(x => x.ReadWrite()
Create a new convention class:
public class CacheableConvention: IClassConventionAcceptance, IClassConvention
{
public void Accept(IAcceptanceCriteria criteria)
{
criteria.Expect(x => x.EntityType.IsNotAny(typeof(Content), typeof(InstanceSetting), typeof(Profanity)));
}
public void Apply(IClassInstance instance)
{
instance.Cache.ReadWrite();
}
}
Add the convention to the AutoMappings.
Done!

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.

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

How do you automap List<float> or float[] with Fluent NHibernate?

Having successfully gotten a sample program working, I'm now starting
to do Real Work with Fluent NHibernate - trying to use Automapping on my project's class
heirarchy.
It's a scientific instrumentation application, and the classes I'm
mapping have several properties that are arrays of floats e.g.
private float[] _rawY;
public virtual float[] RawY
{
get
{
return _rawY;
}
set
{
_rawY = value;
}
}
These arrays can contain a maximum of 500 values.
I didn't expect Automapping to work on arrays, but tried it anyway,
with some success at first. Each array was auto mapped to a BLOB
(using SQLite), which seemed like a viable solution.
The first problem came when I tried to call SaveOrUpdate on the
objects containing the arrays - I got "No persister for float[]"
exceptions.
So my next thought was to convert all my arrays into ILists e.g.
public virtual IList<float> RawY { get; set; }
But now I get:
NHibernate.MappingException: Association references unmapped class: System.Single
Since Automapping can deal with lists of complex objects, it never
occured to me it would not be able to map lists of basic types. But
after doing some Googling for a solution, this seems to be the case.
Some people seem to have solved the problem, but the sample code I
saw requires more knowledge of NHibernate than I have right now - I
didn't understand it.
Questions:
1. How can I make this work with Automapping?
2. Also, is it better to use arrays or lists for this application?
I can modify my app to use either if necessary (though I prefer
lists).
Edit:
I've studied the code in Mapping Collection of Strings, and I see there is test code in the source that sets up an IList of strings, e.g.
public virtual IList<string> ListOfSimpleChildren { get; set; }
[Test]
public void CanSetAsElement()
{
new MappingTester<OneToManyTarget>()
.ForMapping(m => m.HasMany(x => x.ListOfSimpleChildren).Element("columnName"))
.Element("class/bag/element").Exists();
}
so this must be possible using pure Automapping, but I've had zero luck getting anything to work, probably because I don't have the requisite knowlege of manually mapping with NHibernate.
Starting to think I'm going to have to hack this (by encoding the array of floats as a single string, or creating a class that contains a single float which I then aggregate into my lists), unless someone can tell me how to do it properly.
End Edit
Here's my CreateSessionFactory method, if that helps formulate a
reply...
private static ISessionFactory CreateSessionFactory()
{
ISessionFactory sessionFactory = null;
const string autoMapExportDir = "AutoMapExport";
if( !Directory.Exists(autoMapExportDir) )
Directory.CreateDirectory(autoMapExportDir);
try
{
var autoPersistenceModel =
AutoMap.AssemblyOf<DlsAppOverlordExportRunData>()
.Where(t => t.Namespace == "DlsAppAutomapped")
.Conventions.Add( DefaultCascade.All() )
;
sessionFactory = Fluently.Configure()
.Database(SQLiteConfiguration.Standard
.UsingFile(DbFile)
.ShowSql()
)
.Mappings(m => m.AutoMappings.Add(autoPersistenceModel)
.ExportTo(autoMapExportDir)
)
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory()
;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
return sessionFactory;
}
I would probably do a one to many relationship and make the list another table...
But maybe you need to rethink your object, is there also a RawX that you could compose into a RawPoint? This would make a table with 3 columns (ParentID, X, Y).
The discontinuity comes from wanting to map a List to a value that in an RDBMS won't go in a column very neatly. A table is really the method that they use to store Lists of data.
This is the whole point of using an ORM like NHibernate. When doing all the querying and SQL composition by hand in your application, adding a table had a high cost in maintenance and implementation. With NHibernate the cost is nearly 0, so take advantage of the strengths of the RDBMS and let NHibernate abstract the ugliness away.
I see your problem with mapping the array, try it with an override mapping first and see if it will work, then you could maybe create a convention override if you want the automap to work.
.Override<MyType>(map =>
{
map.HasMany(x => x.RawY).AsList();
})
Not sure if that will work, I need to get an nHibernate testing setup configured for this stuff.
Since I posted my question, the Fluent NHibernate team have fixed this problem.
You can now automap ILists of C# value types (strings, ints, floats, etc).
Just make sure you have a recent version of FNH.
Edit
I recently upgraded from FNH 1.0 to FNH 1.3.
This version will also automap arrays - float[], int[], etc.
Seems to map them as BLOBs. I assume this will be more efficient than ILists, but have not done any profiling to confirm.
I eventually got an override to work - see the end of the code listing. The key points are:
a new mapping class called DlsAppOverlordExportRunDataMap
the addition of a UseOverridesFromAssemblyOf clause in
CreateSessionFactory
Also, it turns out that (at least with v. 1.0.0.594) there is a very big gotcha with Automapping - the mapping class (e.g. DlsAppOverlordExportRunDataMap) cannot be in the same Namespace as the domain class (e.g. DlsAppOverlordExportRunData)!
Otherwise, NHibernate will throw "NHibernate.MappingException: (XmlDocument)(2,4): XML validation error: ..." , with absolutely no indication of what or where the real problem is.
This is probably a bug, and may be fixed in later versions of Fluent NHibernate.
namespace DlsAppAutomapped
{
public class DlsAppOverlordExportRunData
{
public virtual int Id { get; set; }
// Note: List<float> needs overrides in order to be mapped by NHibernate.
// See class DlsAppOverlordExportRunDataMap.
public virtual IList<float> RawY { get; set; }
}
}
namespace FrontEnd
{
// NEW - SET UP THE OVERRIDES
// Must be in different namespace from DlsAppOverlordExportRunData!!!
public class DlsAppOverlordExportRunDataMap : IAutoMappingOverride<DlsAppOverlordExportRunData>
{
public void Override(AutoMapping<DlsAppOverlordExportRunData> mapping)
{
// Creates table called "RawY", with primary key
// "DlsAppOverlordExportRunData_Id", and numeric column "Value"
mapping.HasMany(x => x.RawY)
.Element("Value");
}
}
}
private static ISessionFactory CreateSessionFactory()
{
ISessionFactory sessionFactory = null;
const string autoMapExportDir = "AutoMapExport";
if( !Directory.Exists(autoMapExportDir) )
Directory.CreateDirectory(autoMapExportDir);
try
{
var autoPersistenceModel =
AutoMap.AssemblyOf<DlsAppOverlordExportRunData>()
.Where(t => t.Namespace == "DlsAppAutomapped")
// NEW - USE THE OVERRIDES
.UseOverridesFromAssemblyOf<DlsAppOverlordExportRunData>()
.Conventions.Add( DefaultCascade.All() )
;
sessionFactory = Fluently.Configure()
.Database(SQLiteConfiguration.Standard
.UsingFile(DbFile)
.ShowSql()
)
.Mappings(m => m.AutoMappings.Add(autoPersistenceModel)
.ExportTo(autoMapExportDir)
)
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory()
;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
return sessionFactory;
}
Didn't get any answers here or on the Fluent NHibernate mailing list that actually worked, so here's what I did.
It smells like a horrible hack, but it works. (Whether it will scale up to large data sets remains to be seen).
First, I wrapped a float property (called Value) in a class:
// Hack - need to embed simple types in a class before NHibernate
// will map them
public class MappableFloat
{
public virtual int Id { get; private set; }
public virtual float Value { get; set; }
}
I then declare the properties in other classes that need to be Lists of floats e.g.
public virtual IList<MappableFloat> RawYMappable { get; set; }
NHibernate creates a single database table, with multiple foreign keys, e.g.
create table "MappableFloat" (
Id integer,
Value NUMERIC,
DlsAppOverlordExportRunData_Id INTEGER,
DlsAppOverlordExportData_Id INTEGER,
primary key (Id)
)

Fluent NHibernate: override derived classes not in the base class auto-mapping

The story:
I had class User and class Organization: User. I did not use any mappings for these classes, let FNH do mapping automatically. Then, I added
public class OrganizationMap : IAutoMappingOverride<Organization>
{
public void Override(AutoMap<Organization> mapping)
{
}
}
Notice there're no overrides. So I did not expect any changes in FNH behavior. But I got this (during schema export actually):
NHibernate.MappingException:
(XmlDocument)(2,4): XML validation
error: The element 'class' in
namespace 'urn:nhibernate-mapping-2.2'
has incomplete content. List of
possible elements expected: 'meta,
subselect, cache, synchronize,
comment, tuplizer, id, composite-id'
in namespace
'urn:nhibernate-mapping-2.2'.
The generated Orders.Core.Organization.hbm.xml was really empty:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="">
<class name="Orders.Core.Organization, Orders.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Organizations" xmlns="urn:nhibernate-mapping-2.2" />
</hibernate-mapping>
So, after I reviewed the User.hbm I got the idea - I need to override Organization in the base class like this:
public class UserMap : IAutoMappingOverride<User>
{
public void Override(AutoMap<User> mapping)
{
mapping.JoinedSubClass<Organization>("ColumnId", m => {...}
);
}
}
But, I would better like to do this in a separate mapping override class for Organization... after all, what would the mapping become if I have 5 subclasses all in single Override method.
Is this possible?
Your override is telling FNH that you will manually write the mappings for that class. The error you are getting is because there is nothing being mapped for Organisation (if you look at the generated HBM.xml it will be empty).
What exactly are you wanting to write the override for?
Edit:
In that case, you can do something like this:
public class MyAlteration : IAutoMappingAlteration
{
public void Alter(AutoPersistenceModel model)
{
model.ForTypesThatDeriveFrom<User>(
map => map.HasMany<User>( x => x.Children)
);
}
}
And when configuring fluent nhibernate:
model.Alteration( a => a.Add<MyAlteration>());
Note: This is using the latest codebase of fluent nhibernate (1.0RC).
Turned out that with latest FNH (some revision after RC) this is possible now. I wonder if this is because I asked ;-)
So I had this
mapping.JoinedSubClass<Organization>("UserId", m =>
{
m.HasMany(x => x.Currencies).Element("Currency").AsBag();
}
);
and it stopped working after upgrading to RC. Then I moved this into its own class
public class OrganizationMap : IAutoMappingOverride<Organization>
{
public void Override(AutoMapping<Organization> mapping)
{
mapping.HasMany(x => x.Currencies).Element("Currency").AsBag();
}
}
it started to work again. Just like I wanted! Now I don't even need to indicate JoinedSubClass as this is the default, anyway. I can just override my subclass properties which is cool.
Though it wasn't too easy to figure out why NH started to complain about association of strings... I even thought that .Element is broken in RC. I wonder why JoinedSubClass still has this mapping part if it doesn't completely work.

Generate table indexes using Fluent NHibernate

Is it possible to generate table indexes along with the rest of the database schema with Fluent NHibernate? I would like to be able to generate the complete database DDL via an automated build process.
In more recent versions of Fluent NHibernate, you can call the Index() method to do this rather than using SetAttribute (which no longer exists):
Map(x => x.Prop1).Index("idx__Prop1");
Do you mean indexes on columns?
You can do it manually in your ClassMap<...> files by appending .SetAttribute("index", "nameOfMyIndex"), e.g. like so:
Map(c => c.FirstName).SetAttribute("index", "idx__firstname");
or you can do it by using the attribute features of the automapper - e.g. like so:
After having created your persistence model:
{
var model = new AutoPersistenceModel
{
(...)
}
model.Conventions.ForAttribute<IndexedAttribute>(ApplyIndex);
}
void ApplyIndex(IndexedAttribute attr, IProperty info)
{
info.SetAttribute("index", "idx__" + info.Property.Name");
}
and then do this to your entities:
[Indexed]
public virtual string FirstName { get; set; }
I like the latter. Is is a good compromise between not being non-instrusive to your domain model, yet still being very effective and clear on what is happening.
Mookid's answer is great and helped me a lot, but meanwhile the ever evolving Fluent NHibernate API has changed.
So, the right way to write mookid sample now is the following:
//...
model.ConventionDiscovery.Setup(s =>
{
s.Add<IndexedPropertyConvention>();
//other conventions to add...
});
where IndexedPropertyConvention is the following:
public class IndexedPropertyConvention : AttributePropertyConvention<IndexedAttribute>
{
protected override void Apply(IndexedAttribute attribute, IProperty target)
{
target.SetAttribute("index", "idx__" + target.Property.Name);
}
}
The [Indexed] attribute works the same way now.