Override Id column's auto-increment initial value with Fluent nHibernate AutoMapping - fluent-nhibernate

I'm using Fluent nHibernate AutoMapping for a project and would like to change the initial Id value for one table in my schema from 1 to say 1000 (all other tables I would like to remain with the default behaviour of starting the Id at 1).
I'm guessing that I need to specify this in my IIDConvetion, but am not sure how?
public class PrimaryKeyConvention : IIdConvention
{
public void Apply(IIdentityInstance instance)
{
instance.Column(instance.EntityType.Name + "Id");
instance.GeneratedBy.Native();
}
}
Would really appreciate being pointed in the right direction.

AFAIK this is not supported yet. Your best bet is to implement IAuxiliaryDatabaseObject and set the starting value of the identity to 1000 with sql then add it as last element to the configuration object.

Related

Readonly Strategies with Nhibernate and Fluent Nhibernate

I been reading nhibernate for beginners 3.0 and been reading about common mistakes(a few of them I been making)
I am wondering what are some strategies for making one or more records readonly. Right now I get all the rows back and loop through them making them readonly through session.Readonly().
I like in the book that they do with fluent
class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
SchemaAction.None();
ReadOnly();
// Mappings
}
}
What I am not sure is what happens if I need these records to not be Readonly? To me this means I have to make this exact same mapping minus those 2 lines of code.
So I would like to do this and have ReadonlyEntityMap and EntityMap but I rather not have to duplicate all the settings twice.
Anyone have ideas on how do to this? Or better ideas for readonly?
Using ReadOnly() on your mapping will disable any updates back to the database when you modify the properties of the object.
If you want to apply some sort of ReadOnly and Writeable strategy I would suggest using a Fluent Convention and a marker interface or similar.
You can also apply ReadOnly() to a property if you want to disable writes on just that one property. I use that technique to avoid writing back to Computed Columns in SQL Server.
Something like this:
public interface IReadOnly{} //Mark entities with this interface
public class ReadOnlyConvention
: IClassConvention, IClassConventionAcceptance<IClassInspector>
{
public void Accept(IAcceptanceCriteria<IClassInspector> criteria)
{
criteria.Expect(x => x.EntityType Is IReadOnly);
}
public void Apply(IClassInstance instance)
{
instance.ReadOnly();
}
}
Update:
If you want to do you time conversion thing I would suggest creating an IUserType for your DateTime object which does the conversion to the user time without modifying the underlying data.
Date Time Support in NHibernate
Custom IUserType for DateTime
It depends on what you are trying to achieve. If you are trying to optimize memory consumption you should consider improving your session management strategy or using other performance improvement techniques. You can for example:
Clear the session that loaded your objects and it will release all the memory allocated by first level cache. The objects can later be reattached (Merged) to a new session if needed. This way you don't need objects to be readonly in the first place.
Evict some of the objects when you no longer need them. This will keep the other objects in the first level cache.
Use IStatelessSession which does not use 1st level cache at all.
Again, the answer depends on your application architecture.

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

Is it possible to have a OneToOne relation to a class hierarchy persisted using JoinedBase?

I'd like one of my entities to have a one-to-one relationship with a class hierarchy. Think of it like a Strategy pattern, where each strategy needs different parameters to be persisted. I tried using a combination of OneToOne and JoinedBase/JoinedKey, but I've come across a problem.
With this combination, the primary key of the main entity also appears as the primary key of the table representing the root class in the hierarchy, and as the primary key of the subclass:
Order --------------- TaxCalculator
([PrimaryKey]Id = 1234) ([PrimaryKey(PrimaryKeyType.Foreign)]OrderId = 1234)
^
|
|
UkTaxCalculator
([JoinedKey]UkTaxCalculatorId = 1234)
I can persist this fine, but then I can't change which subclass of TaxCalculator I have. When I do something like:
order.TaxCalculator = new OverseasTaxCalculator(order);
then try to flush, then ActiveRecord/NHibernate (understandably) gets unhappy that there are now two TaxCalculators with Id = 1234.
I can get around this by replacing the OneToOne with a HasMany/BelongsTo, and hiding the multiplicity from users of the Order object, but I'm interested to know if it's possible to do this with OneToOne.
There's a full code example on github. This code throws an exception when the second SessionScope is disposed. If you clone the project, it should run out-of-the-box.
first of all i am sorry, but i did not tried my solution. It is to late and i really need my sleep ;-). I think the only way the one-to-one could work would be a 'table-per-hierarchy'-approach using a discriminator column instead of table-per-subclass. Maybe this will enable you to morph the existing object to another subclass. An other way, something like a polymorphic delete-orphan unfortunately is not supported as you stated. So i'll guess this would be your (very) last option.
But if this fails why don't you map it as a one-to-many instead of many-to-one with a foreign key in the order table, reusing the TaxCalculators? I would imagine them as quite static.
Interesting idea though: polymorphic delete-orphan.
We do something very similar to what you are trying to do. I think it's your combination of one-to-one and the joined key that's causing the problem. Try this:
[ActiveRecord, JoinedBase]
public class TaxCalculator
{
protected int TaxCalculatorId;
[PrimaryKey]
public virtual int Id
{
get { return TaxCalculatorId; }
set { TaxCalculatorId = value; }
}
// common tax calculation fields, methods etc...
}
[ActiveRecord]
public class OverseasTaxCalculator : TaxCalculator
{
[JoinedKey]
public override int Id
{
get { return TaxCalculatorId; }
set { TaxCalculatorId = value; }
}
// overseas tax calculation specific methods, properties etc...
}

fluent nhibernate automap version column

Current code in my convention:
public void Apply(FluentNHibernate.Conventions.Instances.IVersionInstance instance)
{
instance.Column("RowVersion");
instance.Not.Nullable();
instance.UnsavedValue("0");
instance.Default(1);
}
This doesn't render the RowVersion as a version column. It treats RowVersion as just another column.
So my question is how do you add Row Version Concurrency using Fluent Nhibernate?
The VersionStep class only looks for properties that match the names of Version or Timestamp. Your property will have to match that name. Replacing VersionStep to change the naming rules is another option.

Fluent NHibernate — specify table/column names when using HiLo generator

Yes, nit-picky is a good way to describe this... ;)
Does anyone know if you can specify the table and/or column names to use HiLo using Fluent NHibernate? Currently the schema export creates this...
create table hibernate_unique_key (
next_hi INTEGER
)
Figured it out...
public class IdGenerationConvention : IIdConvention
{
public void Apply(IIdentityInstance instance)
{
instance.GeneratedBy.HiLo("MyTableName", "NextHighValue", "1000");
}
}