I have a scenario where a class called “Comment” references an abstract type called “Entity”. The Fluent-ClassMap looks quite similar to the following for the property “Entity”:
classMap.ReferencesAny(x => x.Entity)
.EntityTypeColumn("DiscriminatorType")
.EntityIdentifierColumn("DiscriminatorId")
.IdentityType<int>()
.AddMetaValue(typeof(Car), typeof(Car).Name);
.AddMetaValue(typeof(House), typeof(House).Name);
As you might have already discovered from the example above the class “Entity” is subclassed by a class named “House” and a class called “Car”. With this setup it is rather trivial to retrieve all comments for a specifc “Entity” by simply doing something like the following: Session.Query().Where(m => m.Entity == myCarObject).ToList(). Everything works like a charm.
Here is the simplified class structure:
abstract class Entity{}
class Car : Entity{}
class House : Entity{}
class Comment
{
public virtual Entity { get; set;}
}
However, in one use case I need to retrieve all instances of “Comment” that reference any “Car”. In other words I’m trying to achieve something like the following:
var allCommentsOnCars1 = Session.Query<Comment>().Where(m => m.Entity is Car); //or
var allCommentsOnCars2 = Session.Query<Comment>().Where(m => m.Entity.GetType() == typeof(Car));
Both examples are not working (the latter throws a GetType() is not implemented exception), but is it possible to solve this anyhow? Very likely I could easily clear my problems by creating two seperate tables: One for all the “Cars” comments as well as one for all the “Houses” comments, but I would rather not change the database structure nor the models at this moment.
Your feedback would be greatly appreciated.
Probably not the most elegant solution, but I solved the problem by simply using QueryOver() instead of Query().