Reference an object from a column in another table - nhibernate

I have the following object model:
class ObjectA{
public string Description {get;set;}
}
class ObjectB{
public string Description {get;set;}
public ObjectA A {get;set;}
}
class ObjectC{
public string Description {get;set;}
public ObjectB B {get;set;}
}
class ObjectD{
public string Description {get;set;}
public ObjectC C {get;set;}
public ObjectA A {get;set;}
}
My tables are as follows:
A: ID(int), DESCRIPTION(string)
B: ID(int), DESCRIPTION(string), A_ID(int)
C: ID(int), DESCRIPTION(string), B_ID(int)
D: ID(int), DESCRIPTION(string), C_ID(int), A_ID(int)
In table D A_ID is a foreign key to the primary key of table A. This was originally done so that you could easily access ObjectA from ObjectD: ObjectD.A. This is causing the ID from table A to have to be added to every table that wants to access ObjectA in this manner de-normalizing the database (imagine having ObjectE, and ObjectF that all want to easily access ObjectA). In this case ObjectB will always have a reference to ObjectA.
I'd like to get rid of the reference to A_ID in all of my tables but I want to be able to easily access ObjectA from my classes. I know I could do ObjectD.ObjectC.ObjectB.ObjectA to get ObjectA when needed but that seems to defeat the purpose of lazy loading my objects.
How can I map my ObjectD so that I can have direct access to ObjectA without having ObjectA's ID in ObjectD's table?
Note: I'm using hbm/xml files to map my classes.

It seems to me you either live with the redundant data for performance reasons or you don't. I can't conceive of a third option. (But there are better NHibernate minds out there that may correct this view).
If the reads of these objects are much higher than the writes and the use cases require access to ObjectA most of the time you're working with an ObjectD then the redundancy is fine. Otherwise the ObjectD.C.B.A approach you refer starts to become more attractive.

Related

Is this a legitimate use of TPC inheritance in EF Code First?

I'm designing a fairly complex hosted web app that needs to support multiple "Teams" that are effectively isolated from each other. For example, the tables People, Areas, Reports, etc. will have intermingled data populated by the teams at Corporation A, B, C, and on down the line, and the user from Corporation A has logged in, he should only ever see data relevant to corporation A. My plan is to create a relationship between Team and (nearly) every other type and to use a repository to access all those other types, and always query where TeamId matches the TeamId of the person logged in.
So since I want to have
[ForeignKey("Team")]
public int TeamId { get; set; }
public virtual Team Team { get; set; }
on almost every class, I was thinking it might be nice to put those in an abstract class and inherit those properties:
public abstract class OfTeam {
[ForeignKey("Team")]
public int TeamId { get; set; }
public virtual Team Team { get; set; }
}
public class Person : OfTeam {
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
But, I realize this isn't truly what inheritance is about. So I'd like to know
Will this even work?
Is it a terrible idea?
I misunderstood at first and though you were inheriting team, which would have been a bad idea.
If you ever query db.OfTeam then it will union together every single table that inherits from it, which will perform terribly. Scroll down to see the SQL produced here:
http://weblogs.asp.net/manavi/archive/2011/01/03/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines.aspx
Otherwise the actual DB structure should be identical to if you simply put TeamId/Team on all of those classes directly.
I personally wouldn't do this because it adds little value and could potentially cause headaches down the road.
Instead you could just have an IOfTeam interface on all those classes if there is a need to interact with them in a generic manner for some reason.
As a side note I've done something similar and usually cache TeamId somewhere easily accessible, such that I can anywhere do CurrentIdentity.TeamId and pass it to a query. This allows methods on repository pattern like GetPeople to apply a where criteria with that filter before returning the IQueryable.

Fluent NHibernate automapping: One-to-many entities, many-to-many backend?

My goal is to use NHibernate schema generation along with Fluent NHibernate's automapper to generate my database. I'm having trouble with what I'll call "unidirectional many-to-many relationships."
Many of my entities have localized resources. A single class might look like this:
public class Something {
public virtual int Id {get; private set;}
public virtual Resource Title {get;set;}
public virtual Resource Description {get;set;}
public virtual IList<Resource> Bullets {get;set;}
}
The Resource class doesn't have any references back; these are entirely unidirectional.
public class Resource {
public virtual int Id {get; private set;}
public virtual IList<LocalizedResource> LocalizedResources {get;set;}
// etc.
}
public class LocalizedResource { //
public virtual int Id {get; private set; }
public virtual string CultureCode {get;set;}
public virtual string Value {get;set;}
public virtual Resource Resource {get;set;}
}
Without the IList<Resource>, everything is generated as I'd want -- Resource ID's are in the Title and Description fields. When I add in the IList though, NHibernate adds the field something_id to the Resource table. I understand why it does this, but in this situation it's not a sustainable approach.
What I want is to create a junction table for the bullets. Something like:
CREATE TABLE SomethingBullet (
Id int NOT NULL PRIMARY KEY IDENTITY(1,1),
Something_Id int NOT NULL,
Resource_Id int NOT NULL
)
This way when I add the other twenty-odd entities into the database I won't end up with a ridiculously wide and sparse Resource table.
How do I instruct the Automapper to treat all IList<Resource> properties this way?
Every many-to-many is in fact composed with one-to-many's in object model. If your relationship doesn't need to be bidirectional, just don't map the second side. The mapping on your mapped side is not affected at all:
HasManyToMany(x => x.Bullets).AsSet();
In this case, NHibernate already knows that it needs to generate the intermediate table.
See also this article for many-to-many tips.
:)
The only way I found to make this work with automapping is by constructing your own custom automapping step and replacing the "native" HasManyToManyStep. It's either that or an override, I'm afraid.
I lifted mine off of Samer Abu Rabie, posted here.
The good news is that Samer's code, so far, seems to work flawlessly with my conventions and whatnots, so, once it was in place, it was completely transparent to everything else in my code.
The bad news is that it costs you the ability to have unidirectional one-to-many relationships, as Samer's code assumes that all x-to-many unidirectional relationships are many-to-many. Depending on your model, this may or may not be a good thing.
Presumably, you could code up a different implementation of ShouldMap that would distinguish between what you want to be many-to-many and what you want to be one-to-many, and everything would then work again. Do note that that would require having two custom steps to replace the native HasManyToManyStep, although, again, Samer's code is a good starting point.
Let us know how it goes. :)
Cheers,
J.

Composition over Inheritance - where do extra properties go?

Take this following code from an example HR system. The user has the ability to log an absence and can be of various types including holiday and sickness. This would be a domain model over an ORM such as NHibernate.
public class Absence
{
public long Id {get;set;}
public Employee Employee {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public virtual void DoSomething()
{ ... }
}
public class Holiday : Absence
{
public string Location {get;set;}
public override void DoSomething()
{ ... }
}
public class Sickness : Absence
{
public bool DoctorsNoteProvided {get;set;}
public override void DoSomething()
{ ... }
}
This is an example - please don't question why location would be required, assume it is a specification.
The user wants to change the type - he thought the employee was off sick but then remembered it was a holiday. Again, you may think this is a bad design but treat it like a requirement - this represents a problem that has come up many times for me.
The problem is that you cannot change the type of an object from Sickness to Absence. Generally, the advice would be to Favour Composition Over Inheritance (Gang of Four) and do this:
public class Absence
{
public long Id {get;set;}
public Employee Employee {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public AbsenceType Type {get;set;}
public void DoSomething()
{
Type.DoSomething();
}
}
But when I do this, when do the properties specific to Holiday and Sickness go (Location and DoctorsNoteProvided respectively)?
Why do you need to change the type of an object?
You will have some kind of collection of Absences, just replace the item in question.
Conceivably rather than replacing you even keep the original request and mark it as superceded, that might be important for audit trail purposes.
It's not the right place for Composition over Inheritance. Here the inheritance is appropriate. And if you need to change the type of absence just create a new one and delete old.
Hmmm, without knowing more about your requirements, I would say the right design is not to change an Absence object to a Sickness object (or vice versa) but to just delete the one you don't want and create a new one of the type you do. Somewhere you must be maintaining a collection of absences, right?
You are correct that classes don't change.
I would model this by having a type hierarchy for an AbsenceType, or AbsenseReason:
abstract class AbsenseReason {
}
class HolidayAbsenseReason : AbsenseReason {
public string Name { get; }
}
I like this model because now AbsenseReason is a value object and is independent of an employee Absence, which is an entity object. This, as you stated, solves the issue with changing the absence reason. Generally speaking, I would favor this over deleting a record, because there may be many associations to consider as well.
Things to consider:
NHibernate does not support inheritance mappings on components so you will have to provide a custom implementation of IUserType.
Consider storing all the data for the different absence reason sub types together with the record for the employee absence entity. Possibly as XML so that you can have collections, etc.
So try to move all type specific functionality to AbsenceType derivatives. If they require something from parent class Absence, you could pass them its reference. Though I would try to avoid that.
If you manipulated Absence object via base class interface, nothing changes, you can keep your old code. Now, if you manipulated specific derivatives, then you will have to grab AbsenceType object from specific Absence and do all the same things on them - still not much to change. If you had holiday.DoSomething(), now you have holiday.Type.DoSomething().

NHibernate convert subclass to parent class

Supposing the following entities :
public class AppUser
{
public virtual int Id { get; set; }
public virtual string Login { get; set; }
}
// Mapped as joined-subclass
public class Person : AppUser
{
public virtual int Age { get; set; }
}
If I create 1 AppUser, and save it like this
var user = new AppUser() { Login = "test" };
session.Save( user ); // let's say Id = 1
How can I cast/convert/"promote" it to a Person, keeping the same ID ?
Now, i'm stuck with a row in my AppUser table, with Id = N. How can I populate the Person table with the same Id ? I can't delete the AppUser and recreate it as a Person, as AppUser may be referenced by foreign keys.
I could issue a "manual" SQL INSERT, but it's kind of ugly...
This is definitively a NHibernate question. I understand that from an OOP point of view, this makes little sense, hence the absence of other tags than nhibernate.
I don't believe nHibernate is going to be able to solve this problem for you. nHibernate is dealing with your data as an object and, especially with joined-subclass I don't believe there is anything built in that allows you to change the subclass type on the fly, or at least change the type and retain the original ID.
I think your best bet is to write a stored procedure that, given an ID and a NEW type, removes all entries from subclass tables and adds a new entry to the correct subclass table.
Once that proc runs, then reload the object in nHibernate (and make sure you have thrown away any cached data relating to it), it should now be of the correct type you want to work with, set its NEW properties and save it.
That way you have a relatively generic stored proc that just changes your subclass types, but you dont need to add all the crazy logic to handle various properties on your subclasses.
This has been discussed on SO before and I am quoting Jon Skeet for posterity:
No. A reference to a derived class
must actually refer to an instance of
the derived class (or null). Otherwise
how would you expect it to behave?
For example:
object o = new object();
string s = (string) o;
int i = s.Length; // What can this sensibly do?
If you want to be able to convert an
instance of the base type to the
derived type, I suggest you write a
method to create an appropriate
derived type instance. Or look at your
inheritance tree again and try to
redesign so that you don't need to do
this in the first place.
In Skeet's example, string's are objects and objects are not strings. So the "upcasting" would not work.

nHibernate Share References?

I'm getting the following exception when saving an object:
Found shared references to a collection
Does anyone know what this means?
In theory it means that you have 2 records which contain the same reference to another object. At the database level this is most likely a weak entity, however at the code level this is likely to be represented as a collection.
Have you copied another records collection?
E.g.
Blog blog1 = Blog.Find(1);
Blog blog2 = new Blog();
blog2.Entries = blog1.Entries;
blog2.Save();
This code is for ActiveRecords, but as it is built on top of nHibernate the underlying principles are the same.
The interesting thing when i came across this issue was that the collection it referred to was incorrect. It was a different one.
If this is your issue try iterating through each item and assigning it to the new collection in stead. E.g.
Blog blog1 = Blog.Find(1);
Blog blog2 = new Blog();
foreach (BlogEntry entry in blog1.Entries)
blog2.Entries.Add(entry);
blog2.Save();
quick google says
rel Group n --- 1 User
m ^
| | inh
| rel |
--------- n Member
rel stands for relation (association)
inh stands for inheritance
The exception is thrown after Member
objects have successfully been created
and then have been read from the
database. After the last Member object
was read the transaction is committed
but this fails.
what do your mappings look like?
Do you have a reference to any of the objects in the collection somewhere else? Another session, possibly, or even within the same session in another object? Make sure that when you access hibernate, you are controlling the ONLY reference to those objects within any hibernate session.
From my experience, this error occurs when you have a joined-subclass mapping where an inherited property is mapped in both the super- and sub-class. Say you have these objects:
public class Being
{
public string DnaSequence { get; protected set; }
}
public class Animal : Being
{
public IList<Animal> Relatives { get; protected set; }
}
public class Human : Animal
{
public string Name { get; protected set; }
}
In your Human mapping, it's important that you don't map the Relatives property. In a joined-subclass mapping, you should only map properties that are unique to the level in the hierarchy you are mapping:
For Being, you only map the DnaSequence property.
For Animal, you only map the Relatives property.
For Human, you only map the Name property.
If you, by accident, map Relatives in the Human mapping, NHibernate will throw "Found shared references to a collection".