NHibernate Legacy Database Mappings Impossible? - nhibernate

I'm hoping someone can help me with mapping a legacy database. The
problem I'm describing here has plagued others, yet I was unable to
find a real good solution around the web.
DISCLAIMER: this is a legacy DB. I have no control over the composite
keys. They suck and can't be changed no matter much you tell me they
suck. I can't add surrogate keys either. Please don't suggest either of these as they are not options.
I have 2 tables, both with composite keys. One of the keys from one
table is used as part of the key to get a collection from the other
table. In short, the keys don't fully match between the table.
ClassB is used everywhere I would like to avoid adding properties for
the sake of this mapping if possible.
public class ClassA
{
//[PK]
public string SsoUid;
//[PK]
public string PolicyNumber;
public IList<ClassB> Others;
//more properties....
}
public class ClassB
{
//[PK]
public string PolicyNumber;
//[PK]
public string PolicyDateTime;
//more properties
}
I want to get an instance of ClassA and get all ClassB rows that match
PolicyNumber. I am trying to get something going with a one-to-many,
but I realize that this may technically be a many-to-many that I am
just treating as one-to-many.
I've tried using an association class but didn't get far enough to see
if it works. I'm new to these more complex mappings and am looking
for advice. I'm open to pretty much any ideas.
Thanks,
Corey

The easiest way to handle mapping legacy database schemas is to add a surrogate generated primary key (i.e. identity in SQL Server) to each database table and change your existing composite primary keys to unique constraints. This allows you to keep your existing foreign keys and makes the NHibernate mapping easy.
If that's not possible then you may be able to use property-ref in your mappings to accomplish this.
Edit: You can always fall back to an anemic domain model. That is, map each class but exclude the relationships. You would have one data access method to get ClassA by key, and one to get a collection of ClassB by PolicyNumber.

I was eventually able to get the DB team to concede to adding some surrogate keys to the tables I was dealing with. This is the document I used to plead my case.

Related

Fluent NHibernate One-To-Many Cascade Delete if Many-Side is not referenced anywhere else

I have a working solution but would be interested to know if there is a way to achieve this through fluent mapping..
For simplicity, I will use a illustrative example:
class Tag {
string name;
IList<Book> books;
}
class Book {
string title;
Tag primaryTag;
}
There is a business case, where Books are deleted and right now, I query the db to check if any other book references the current tag as primary. If not, I delete the book and after that, I delete the tag because it is not used anywhere else. If the tag is stil used, I only delete the book.
Now it's your turn... do you know a way to achieve this using mappings? I tried the following:
BookMap : ClassMap<Book> {
...
References(x => x.primaryTag)
.Cascade.All() //the collection in TagMap is set to "inverse"
}
But not surprisingly, it throws a foreign key constraint error when the tag is used in other books.
Regards,
Martin
There's no way to do that. NHIbernate is mimicking what you can do in Sql Server config with cascade-deletes. There's no way to go up to a parent and delete "orphans" without using triggers in Sql Server.
There's a way to mimic triggers in NHibernate using "Interceptors" - a way to listen for CRUD on specific Entities and then perform actions. But really it's an anti-pattern since you may as well add the same code to the method that removes the Tag (rather in some hidden/obscure approach like the following, which is usefull for cross-cutting concerns such as Auditing).
This is a really nice article on how to do it (but there's loads out there just google "NHibernate Interceptors").
I'd make sure to use Session.Delete(entity) to ensure deleted entities are removed from Session (for sanity) rather than

How to fix my m..n relationship in nosql (mongodb)?

At first I'm trying to make a rally (you know cars with drivers...) database. I have two collections: drivers { name, address, sex, ... } and then another one tournaments { name, location, price, ... }
I try to keep it simple. In a tournament there should be drivers (because a tournament without drivers...well its not nice ^^). And there is my problem, in a normal sql database I could select two primary keys (lets say name in drivers and name in tournaments - just to keep it simple, I know name as primary key is not nice). And because its an m..n relationship (is it right?) I would make a 3. Table with the two primary keys. OK that would be easy. But how should I solve this problem in mongodb. I thought something like: tournaments { name, location, price, ... drivers { driver_1, ..., driver_n } } , but im not sure. I'm using Java so I could make some special Classes which one is handling this relationship problem? I don't understand the other mongodb tutorials. Any ideas? Thank you for any help!
There are a few ways to do this:
As #Gianluca describes you can perform this linking manually by adding a driver's _id ObjectId or another identifying property (probably one you have a unique index on) to a "drivers" array in a tournament document. e.g. tournament : { ... drivers : ["6019235867192384", "73510945093", ...]}
Another option specifically built for this referencing is the DBRef specification which provides a more formal method probably more similar to what you're familiar in the SQL world. DBRef is supported by the java driver and allows you to scope your reference to a collection (basically saying where this reference comes from). I wouldn't be surprised if in the future versions of MongoDB cross-collection queries will be supported, although they are not currently.
More information here.
Also if you aren't using a DAO framework I would suggest Morphia which supports DBRef with a nice #Reference annotation.
I solved the problem using the _id field that every document had and is unique.
So in you case you just need to create a collection that has the ObjectId of the torunaments and some ObjectId from the collection drivers. Or you can just put the ObejctId of the driver directly in the torunaments collection. Probably not the best solution, but it work
Gianluca
Add an array field drivers in the trournaments type and put the _ids of the drivers in there.
To add/remove drivers, just update the field. There is no need for an intermediary N:M mapping table unless the array gets really huge.
If it gets huge, the usual solution is to cut the array into several smaller ones and save them in several documents that you can look up quickly by using the id_ of the container (the tournament). Removing and sorting is then a pain, of course.

Restricting deletion with NHibernate

I'm using NHibernate (fluent) to access an old third-party database with a bunch of tables, that are not related in any explicit way. That is a child tables does have parentID columns which contains the primary key of the parent table, but there are no foreign key relations ensuring these relations. Ideally I would like to add some foreign keys, but cannot touch the database schema.
My application works fine, but I would really like impose a referential integrity rule that would prohibit deletion of parent objects if they have children, e.i. something similar 'ON DELETE RESTRICT' but maintained by NHibernate.
Any ideas on how to approach this would be appreciated. Should I look into the OnDelete() method on the IInterceptor interface, or are there other ways to solve this?
Of course any solution will come with a performance penalty, but I can live with that.
I can't think of a way to do this in NHibernate because it would require that NHibernate have some knowledge of the relationships. I would handle this in code using the sepecification pattern. For example (using a Company object with links to Employee objects):
public class CanDeleteCompanySpecification
{
bool IsSatisfiedBy(Company candidate)
{
// Check for related Employee records by loading collection
// or using COUNT(*).
// Return true if there are no related records and the Company can be deleted.
// Hope that no linked Employee records are created before the delete commits.
}
}

How to map many columns from one table in database to one array/list in class?

I have a table in database which has some columns like year,name and also 12 columns (m1,m2,...,m12) representing months. I would like to map this table into one class using NHibernate, ideally, these 12 mapped columns would look like:
_mappedMonths[] = new double[12];
Has anyone a solution for this ?
If you really want to map the columns directly to an array, as you describe, take a look at the ICompositeUserType interface. You can find an article about custom NHibernate mapping here, and this blog post might be of interest as well.
However, if it is not super important you might consider mapping the columns just as you normally would, but as private/protected properties, and then create a public property in your class that exposes those private/public properties as an array. That would be a simpler and faster solution, but would result in code that is not quite as clean.

Fluent-NHibernate table mapping with no primary key

I am trying to create a mapping to a database table that has no primary keys/references.
public class TestMap : ClassMap<<Test>Test> {
public TestMap() {
WithTable("TestTable");
Map(x => x.TestColumn);
}
}
This fails and expects id or composite-id. Is this possible in fluent nhibernate?
In Oracle at least, I have used "ROWID" for this. For mssql you might use the "ROW_NUMBER()" builtin function for readonly access to the table, but I haven't tried that...
No. You'll have to add a surrogate primary key, such as an identity column in SQL Server, to map this table. As far as I know, this isn't supported by NHibernate itself.
Why don't you have a primary key on this table?
This functionality isn't supported by nhibernate as far as I know. As a general rule of thumb, however, you should really always have some kind of ID and if you find yourself in a situation where you think you don't need one you should assess your data model. An ID, whether it be a table-specific primary key, or a surrogate key from another table, should exist. This not only ensures that nhibernate can process the table, but helps performance via indexing.
Before you start assuming nhibernate isn't going to fulfill your needs, consider why you don't have a key on the table and what kind of sense it makes not to have one.
If we can bring a column from table having no primary key/identity coulmn, then we can use fluent as below:
Id(x => x.TempID).Column("TempID");
If the table contains data that belongs to another entity, you could map it as a collection of components. Components are not identified by themselves, but they belong to another entity, which is identified.
You can map an entity to a table without keys defined in the database. I do so in legacy SQL Server databases. However, the table must have a candidate key (some set of columns that actually stores a unique combination of values). The concept of entity involves the notion of some kind of identity.
Instead of this, what you're trying in your code is to map an entity without identity, wich isn't possible.