NHibernate.QueryException: not an association: Id - nhibernate

I wrote a joint query using NHiberNate, but I am getting a NHibernate.QueryException:not an association: Id
This is what it looks like with NHibernate library
TicketRequest ticketAlias = null;
Show showAlias = null;
IList<TicketRequest> results = UnitOfWork.CurrentSession.QueryOver<TicketRequest>(() => ticketAlias)
.JoinAlias(() => ticketAlias.ShowId, () => showAlias.Id)
.Where(() => showAlias.ShowDate >=DateTime.Now)
.List();
return results;
I just want a simple joint statement, and this is what it would have been in SQL
select * from TicketRequest as a join Show as b
on a.Show_id = b.Id
where ShowDate >=GETDATE()
Can someone help and let me know why I am getting a "not an association:Id" error. I have id in the "Show" table, it is a primary key.
Please advise. All helps are greatly appreciated.

You need to specify a many-to-one relation in joins. In your case that is the Show property.
IList<TicketRequest> results = UnitOfWork.CurrentSession.QueryOver<TicketRequest>(() => ticketAlias)
.JoinAlias(() => ticketAlias.Show, () => showAlias)
.Where(() => showAlias.ShowDate >= DateTime.Now)
.List();
PS: You shouldn't map both a many-to-one relation (Show) and an foreign key property (ShowID). Usually you only work with object relations when using an ORM. Only map the plain ID if you really need it for something, but even then only map it as read-only.

You don't have to specify the foreign keys / primary keys when querying with NHibernate. It's an ORM. You write object oriented queries. The keys and relations are specified in the mapping file.
A Join in an NHibernate query is simply specified by the property name with which you navigate to the other property.
That's what the error message means. Id is not an association.

Related

Exclude rows not participating in an optional relationship

I have a DB schema as
Episode(id INTEGER)
Study(id INTEGER, id_episode INTEGER (NOT NULL), FOREIGN KEY (id_episode) REFERENCES Episode(id))
Episode table used to have a relationship toward Study and had in code a Criteria query like
sess.CreateCriteria<Episode>.
[…] # multiple filtering criteria added here
.Add(Expression.IsNull("Study"))
Now that the Episode.Study column is gone, how do I request only rows from Episode that are not in relationship with a Study row?
By reading the documentation and the web I have the impression I have to do an outer join onto Study and then filter there, not sure if that is the case or how to express that in the Criteria API.
I am using 5.x.
var criteriaResult = session.CreateCriteria<Episode>("episode")
// more filter
.Add(Subqueries.NotExists(DetachedCriteria.For<Study>().Add(Restrictions.EqProperty("Episode.Id", "episode.Id")).SetProjection(Projections.Id)))
.List();
or
var linqResult = session.Query<Episode>()
// more filter
.Where(e => !session.Query<Study>().Where(s => s.Episode == e).Any())
.ToList();

Lithium with left join

I'm new with Lithium.I need to do a left join.This is the query I need.
SELECT `title`,`body`,`user_id`,`users`.`username`,`users`.`id`
FROM `posts` LEFT JOIN `users`
ON `user_id` = `users`.`id`
I try to do something like this.
$conditions['user_id'] = $this->data['user_id'];
$posts = Post::all(array(
'conditions' => $conditions,
'fields' => array('title','body','username'),
'join' => array('source' => 'posts',
'type' => 'LEFT',
'constraint' => array('post.user_id' => 'Users.id')),
))->data();
There is a great tutorial (using a blog as an example) here which explains using Relationships in Lithium, Relationships make using relational data and JOINS simpler.
You can also check out the official docs as well as this answer: How do I perform joins with lithium models?
Once you have your Relationships set on your Models you can do your JOINS as simply as:
$posts = Posts::find('all', array(
'with' => 'Users'
));
There are a couple differant types of Relationships in Lithium, which roughly corrspond to differant types of JOINS ...
hasOne: the current object is linked to a single object of another type
hasMany: the current object is linked to many objects of another type
belongsTo: the current object is owned and marked as related to
another object

NHibernate mapping in n:n relatinship

Suppose say I have Order, Items, OrderItems tables with Order and Items having n:n relationship and OrderItems being associative table. I have seen below two approaches for defining them.
1.Create Order and Items entities with "HasMany" relationship with OrderItems.
2.Create Order, Items and OrderItems entities with Order and Items having "ManytoMany" relationship and "OrderItems" containing Order and Item properties.
I have approach 1 which works fine but would like to know what approach 2 does.
If the relationship between Items and Orders is simple (merely that the relationship exists), then you would do a ManyToMany mapping between Items.Orders and Orders.Items. This would result in NHibernate generating and managing a simple cross reference table containing the two foreign keys.
On the other hand, if there is additional information that you need to record along with the two foreign keys, you must use a distinct entity or value object to capture that information, using HasMany on both sides.
Classes:
Order
Id
Name
OrderItems
Item
Id
Name
OrderItems
OrderItem
Id
Order
Item
Quantity
Mappings:
Order:
Id(c => c.Id);
Map(c => c.Name);
HasMany(c => c.OrderItems).KeyColumn("OrderId");
Item:
Id(c = c.Id);
Map(c => c.Name);
HasMany(c => c.OrderItems).KeyColumn("ItemId");
OrderItem:
Id(c => c.Id);
Map(c => c.Quantity);
References(c => c.Order);
References(c => c.Item);

How to get same Columns from different tables

I have 3 tables
task (Id,text,Contact_Id)
users(Id,name)
company(id,name)
and 2 junction tables
task_users (task_id,user_id)
task_companies (task_id,company_id)
note: contact_id may be refer to users table or company
How can I get task id, task text, contact name in one Criteria
This's example with QueryOver, but it almost like ICriteria.
Contact contact = null;
mappingSession.QueryOver<Task>()
.JoinAlias(() => task.Contact, () => contact)
.SelectList(list => list
.SelectGroup(task => task.Id)
.Select(task => task.Text)
.Select(() => contact.Name))
.TransformUsing(Transformers.DistinctRootEntity)
.List();
Other is a mapping. You can make base entity "Contact" and extend from it User and Company.

FluentNHibernate: how to Join to table without using primary key

In the following FluentNHibernate mapping:
public LawbaseAssetMap()
{
Table("PRASSET");
Id(x => x.Id).Column("PRA_RECNUM");
Join("PRSTOCK", m =>
{
m.Fetch.Join();
m.Optional();
m.KeyColumn("PRS_ASSRN");
m.Map(t => t.Certificated).Column("PRS_CERT").CustomType("YesNo");
});
}
I am performing an outer join from the table PRASSET to the table PRSTOCK. The join is between PRSTOCK.PRS_ASSRN and PRASSET.PRA_RECNUM (the primary key of PRASSET).
How would I create the equivalent join, but instead of joining onto PRASSET's primary key, join on to another field instead?
David have a look on following link, as i thing that it might help
Fluent NHibernate - Mapping a property to a column on a joined table
also this might help
ReferencesAny(x => x.Author)
.EntityTypeColumn("Type")
.EntityIdentifierColumn("Id")
.IdentityType<int>();
See more here.
Hope this helps... and now really holliday :) see u