Fluent NHibernate: How do you change the underlying sql type for an automapped collection of strings? - nhibernate

I have a class:
public class ParentClass
{
//other stuff
IList<string> ChildPages
}
When 'IList<string> ChildPages' gets automapped by Fluent NHibernate a 'ChildPages' join table is created with a nvarchar(255) backing field for each string in the collection.
But the problem is that I want the sql backing field to be 'text', so that I can have lengthy entries for this entity.
What's the easiest way to make this change?
How do you change the underlying type of automapped primitive collections?
Also, for extra points, how would you do this with a convention or mapping overrides?
Thx!

You can setup an override convention so that strings use text instead of nvarchar2 (255), as shown in the solution on this other thread. If you only want such behavior for a specific property, something like this in your fluent configuration would work:
AutoMap
.AssemblyOf<ParentClass>()
.Override<ChildPage>(map =>
{
mapping.Map(x => x.Page).CustomType("StringClob").CustomSqlType("text");
});

Related

How can I make a where clause on a reference in fluent-nhibernate mapping

There exists such a method on HasMany and HasManyToMany but for some reason there isn't such a mechanism on References.
We have an object that references an other object that can be updated and saved as new versions but from our child object we doesn't really care we only want to load the latest version of the related object. The mapping cannot use the primary key for the related object since this will change for each version of the object so instead we want to map the related object to an property that doesn't change between versions and then make a where-clause to only selected the matching element with the highest version.
So our mapping is like the following
References(p => p.RelatedObjectIdentifier).PropertyRef("MatchingPropIdentifier").Not.Nullable;
We would like to do something like this
References(p => p.RelatedObjectIdentifier).PropertyRef("MatchingPropIdentifier").Where(p => p.IsLatest).Not.Nullable;
Of course we would update the property IsLatest (bool property) for each saving of the related object.
So since the Where(p => p.IsLatest) doesn't exist on a References for a classmap/subclassmap how can we make this happen in any other way?
You can only use the Where() restriction, which:
Defines a SQL 'where' clause used when retrieving objects of this type.
on the class map of the referenced type.
Example:
public class RelatedObjectMap : ClassMap<RelatedObject>
{
public RelatedObjectMap()
{
Table("RelatedObjectTable");
//Id() etc.
Where("MatchingPropIdentifier IS NOT NULL)");
}
}

NHibernate property value null but member value not null

I have a object that has a property that is a reference to another type and uses a camel case private member variable as a backing. When I run my application the property value is being returned as null but if I debug and inspect the field it is not null. Here is what the property looks like:
public virtual FileType FileType
{
get { return this.fileType; }
set { this.fileType = value; }
}
I am using Fluent NHibernate to do the mapping and this is what the mapping looks like:
this.References<FileType>(x => x.FileType)
.Column("FileTypeID")
.LazyLoad()
.Cascade.SaveUpdate()
.Access.CamelCaseField();
I have other object with the exact same layout as this one and they work but for some reason this particular object property always return null. Has anyone ever seen anything like this and would be able to give me some idea how to fix it?
I had the same issue, out of curiosity I upgraded NHibernate from version 3.3.1.4000 to NHibernate 3.4.1.4000 as I thought it had to be a bug in either NHibernate or Fluent and it went away so assume it was a bug in NHibernate. Just for extra information, I am targeting FluentNhibernate version 1.4.0.0.

Serialize array of simple types into a single database field

Is it possible to configure NHibernate (specifically Fluent NHibernate) to serialize an array of simple types to a single database column? I seem to remember that this was possible but its been a while since I've used NHibernate.
Essentially I need to store the days of week that a person works (int[]) and would rather not have a separate table just for this purpose.
It is possible.
You need to implement a IUserType that takes care of mapping between your array and a data column (google that first; it's possible that somebody already implemented it)
Alternatively, you can do the conversion in your entity class, and map the single-field representation instead of the property. For example:
string numbers;
public int[] Numbers
{
get { return numbers.Split(','); }
set { numbers = string.Join(",", value.Select(x => x.ToString())); }
}
Yes. There's UserType for scenarios like that. You could also use enum and bit flag.

Accept Interface into Collection (Covariance) troubles with nHibernate

I am using Fluent nHibernate for my persistence layer in an ASP.NET MVC application, and I have come across a bit of a quandry.
I have a situation where I need to use an abstraction to store objects into a collection, in this situation, an interface is the most logical choice if you are looking at a pure C# perspective.
Basically, an object (Item) can have Requirements. A requirement can be many things. In a native C# situation, I would merely accomplish this with the following code.
interface IRequirement
{
// methods and properties neccessary for evaluation
}
class Item
{
virtual int Id { get; set; }
virtual IList<IRequirement> Requirements { get; set; }
}
A crude example. This works fine in native C# - however because the objects have to be stored in a database, it becomes a bit more complicated than that. Each object that implements IRequirement could be a completely different kind of object. Since nHibernate (or any other ORM that I have discovered) cannot really understand how to serialize an interface, I cannot think of, for the life of me, how to approach this scenario. I mean, I understand the problem.
This makes no sense to the database/orm. I understand completely why, too.
class SomeKindOfObject
{
virtual int Id { get; set; }
// ... some other methods relative to this base type
}
class OneRequirement : SomeKindOfObject, IRequirement
{
virtual string Name { get; set; }
// some more methods and properties
}
class AnotherKindOfObject
{
virtual int Id { get; set; }
// ... more methods and properties, different from SomeKindOfObject
}
class AnotherRequirement : AnotherKindOfObject, IRequirement
{
// yet more methods and properties relative to AnotherKindOfObject's intentive hierarchy
}
class OneRequirementMap : ClassMap<OneRequirement>
{
// etc
Table("OneRequirement");
}
class AnotherRequirementMap : ClassMap<AnotherRequirement>
{
//
Table("OtherRequirements");
}
class ItemMap : ClassMap<Item>
{
// ... Now we have a problem.
Map( x => x.Requirements ) // does not compute...
// additional mapping
}
So, does anyone have any ideas? I cannot seem to use generics, either, so making a basic Requirement<T> type seems out. I mean the code works and runs, but the ORM cannot grasp it. I realize what I am asking here is probably impossible, but all I can do is ask.
I would also like to add, I do not have much experience with nHibernate, only Fluent nHibernate, but I have been made aware that both communities are very good and so I am tagging this as both. But my mapping at present is 100% 'fluent'.
Edit
I actually discovered Programming to interfaces while mapping with Fluent NHibernate that touches on this a bit, but I'm still not sure it is applicable to my scenario. Any help is appreciated.
UPDATE (02/02/2011)
I'm adding this update in response to some of the answers posted, as my results are ... a little awkward.
Taking the advice, and doing more research, I've designed a basic interface.
interface IRequirement
{
// ... Same as it always was
}
and now I establish my class mapping..
class IRequirementMap : ClassMap<IRequirement>
{
public IRequirementMap()
{
Id( x => x.Id );
UseUnionSubclassForInheritanceMapping();
Table("Requirements");
}
}
And then I map something that implements it. This is where it gets very freaky.
class ObjectThatImplementsRequirementMap : ClassMap<ObjectThatImplementsRequirement>
{
ObjectThatImplementsRequirementMap()
{
Id(x => x.Id); // Yes, I am base-class mapping it.
// other properties
Table("ObjectImplementingRequirement");
}
}
class AnotherObjectThatHasRequirementMap : ClassMap<AnotherObjectThatHasRequirement>
{
AnotherObjectThatHasRequirementMap ()
{
Id(x => x.Id); // Yes, I am base-class mapping it.
// other properties
Table("AnotheObjectImplementingRequirement");
}
}
This is not what people have suggested, but it was my first approach. Though I did it because I got some very freaky results. Results that really make no sense to me.
It Actually Works... Sort Of
Running the following code yields unanticipated results.
// setup ISession
// setup Transaction
var requirements = new <IRequirement>
{
new ObjectThatImplementsRequirement
{
// properties, etc..
},
new AnotherObjectThatHasRequirement
{
// other properties.
}
}
// add to session.
// commit transaction.
// close writing block.
// setup new session
// setup new transaction
var requireables = session.Query<IRequirable>();
foreach(var requireable in requireables)
Console.WriteLine( requireable.Id );
Now things get freaky. I get the results...
1
1
This makes no sense to me. It shouldn't work. I can even query the individual properties of each object, and they have retained their type. Even if I run the insertion, close the application, then run the retrieval (so as to avoid the possibility of caching), they still have the right types. But the following does not work.
class SomethingThatHasRequireables
{
// ...
public virtual IList<IRequirement> Requirements { get; set; }
}
Trying to add to that collection fails (as I expect it to). Here is why I am confused.
If I can add to the generic IList<IRequirement> in my session, why not in an object?
How is nHibernate understanding the difference between two entities with the same Id,
if they are both mapped as the same kind of object, in one scenario, and not the other?
Can someone explain to me what in the world is going on here?
The suggested approach is to use SubclassMap<T>, however the problem with that is the number of identities, and the size of the table. I am concerned about scalability and performance if multiple objects (up to about 8) are referencing identities from one table. Can someone give me some insight on this one specifically?
Take a look at the chapter Inheritance mapping in the reference documentation. In the chapter Limitations you can see what's possible with which mapping strategy.
You've chose one of the "table per concrete class" strategies, as far as I can see. You may need <one-to-many> with inverse=true or <many-to-any> to map it.
If you want to avoid this, you need to map IRequirement as a base class into a table, then it is possible to have foreign keys to that table. Doing so you turn it into a "table per class-hierarchy" or "table per subclass" mapping. This is of course not possible if another base class is already mapped. E.g. SomeKindOfObject.
Edit: some more information about <one-to-many> with inverse=true and <many-to-any>.
When you use <one-to-many>, the foreign key is actually in the requirement tables pointing back to the Item. This works well so far, NH unions all the requirement tables to find all the items in the list. Inverse is required because it forces you to have a reference from the requirement to the Item, which is used by NH to build the foreign key.
<many-to-any> is even more flexible. It stores the list in an additional link table. This table has three columns:
the foreign key to the Item,
the name of the actual requirement type (.NET type or entity name)
and the primary key of the requirement (which can't be a foreign key, because it could point to different tables).
When NH reads this table, it knows from the type information (and the corresponding requirement mapping) in which other tables the requirements are. This is how any-types work.
That it is actually a many-to-many relation shouldn't bother you, it only means that it stores the relation in an additional table which is technically able to link a requirement to more then one item.
Edit 2: freaky results:
You mapped 3 tables: IRequirement, ObjectThatImplementsRequirement, AnotherObjectThatHasRequirement. They are all completely independent. You are still on "table per concrete class with implicit polymorphism". You just added another table with containing IRequirements, which may also result in some ambiguity when NH tries to find the correct table.
Of course you get 1, 1 as result. The have independent tables and therefore independent ids which both start with 1.
The part that works: NHibernate is able to find all the objects implementing an interface in the whole database when you query for it. Try session.CreateQuery("from object") and you get the whole database.
The part that doesn't work: On the other side, you can't get an object just by id and interface or object. So session.Get<object>(1) doesn't work, because there are many objects with id 1. The same problem is with the list. And there are some more problems there, for instance the fact that with implicit polymorphism, there is no foreign key specified which points from every type implementing IRequirement to the Item.
The any types: This is where the any type mapping comes in. Any types are stored with additional type information in the database and that's done by the <many-to-any> mapping which stores the foreign key and type information in an additional table. With this additional type information NH is able to find the table where the record is stored in.
The freaky results: Consider that NH needs to find both ways, from the object to a single table and from the record to a single class. So be careful when mapping both the interface and the concrete classes independently. It could happen that NH uses one or the other table depending on which way you access the data. This may have been the cause or your freaky results.
The other solution: Using any of the other inheritance mapping strategies, you define a single table where NH can start reading and finding the type.
The Id Scope: If you are using Int32 as id, you can create 1 record each second for 68 years until you run out of ids. If this is not enough, just switch to long, you'll get ... probably more then the database is able to store in the next few thousand years...

Enum to integer mapping causing updates on every flush

I am trying to map an enum property (instance of System.DayOfWeek) in my model to an integer database field.
Other enum properties in the model should be mapped to strings, so I don't wish to define a convention.
I understand that this should be possible using a fluent mapping like:
Map(x => x.DayOfWeek).CustomType<int>();
and indeed, at first glance this appears to be working.
However, I noticed that instances of entities with properties mapped in this way are being updated every time the session was flushed, even though no amendments have been made to them.
To find out what is causing this flush, I set up an IPreUpdateEventListener, and inspected the OldState and State of the entity.
See the attached image. In the OldState, the relevant object is an int, whereas in State it is a DayOfWeek.
If I use an HBM XML mapping with no type attribute specified, this issue doesn't arise.
So...
Is this a bug or shortcoming in the GenericEnumMapper?
Is there any way of telling the FNH mapping not to specify any type attribute on the generated HBM?
If not, can I specify the default type that NH uses for enums (and what is that)?
If you use my enum convention you don't have that problem.
public class EnumConvention : IPropertyConvention, IPropertyConventionAcceptance
{
public void Apply(IPropertyInstance instance)
{
instance.CustomType(instance.Property.PropertyType);
}
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType == typeof(AddressType) ||
x.Property.PropertyType == typeof(Status) ||
x.Property.PropertyType == typeof(DayOfWeek));
}
}
You can then map your property like regular:
Map(x => x.DayOfWeek);
EDIT : Updated the convention to pick specific enums to use for the int conversion. All enums that are not checked here would be mapped as string. You might have to experiment a little with what to actually test against. I am unsure if the propertytype will do it directly.
I know I'm late to the party - it's been two years since the question. But since I've stumbled upon this, I might just add solved the problem for me:
Map(x => x.DayOfWeek).CustomType<enumType>();
It did the trick for me: it stopped updating every time.
Source: https://groups.google.com/forum/#!searchin/fluent-nhibernate/enum/fluent-nhibernate/bBXlDRvphDw/AFnYs9ei7O0J
One workaround that I use is to have an int backing field and letting NHibernate use that for mapping.
Whenever NHibernate has to do a cast to compare the new value with the old one - it is always marked as dirty - causing the flush.
Simple way that worked for me was to change mapping's custom type from int to PersistentEnumType. Make sure to declare a generic version to make your life easier:
public class PersistentEnumType<T> : PersistentEnumType {
public PersistentEnumType() : base(typeof(T)) {}
}
Then use
Map(x => x.DayOfWeek)
.CustomType<PersistentEnumType<System.DayOfWeek>>();
This does not require changes to your entities, only mappings, and can be applied on a per-property basis.
See more here.
It depends on if you need to have DayOfWeek specifically as an integer.
If you're casting as part of the mapping, equality will always fail, and the property will be marked as dirty.
I'd probably map:
Map(x => x.DayOfWeek).CustomType();
and create a read only property that presents the DayOfWeek value as an integer if it's really required. Regardless, mapping as the actual type should work and prevent false-dirty.
You might consider an alternate approach; I have found the usage of Fabio Maulo's well known instance types to be invaluable for such uses. The benefit of these is immediately apparent any time you find yourself trying to extend what a basic enum can do (eg. providing a localized description, etc.)