views:

350

answers:

1

We are adding an attribute(tags) to a system. The attribute table is just a relation table without any foreign keys. Is there a way to add to the criteria to generate a where clause for the attribute table on a parent table.

<class name="Account" table="dbo.Account" lazy="true" >
    <id name="Id" column="`AccountId`">
     <generator class="int"/> 
    </id>
    <property name="Name" column="`Name`" />
    <property name="Address" column="`Address`" />
</class>

<class name="Attribute" table="dbo.Attribute" lazy="true" >
    <id name="Id" column="`AttributeId`">
     <generator class="int"/> 
    </id> 
    <property name="Name" column="`Name`" />
    <property name="LinkId" column="`LinkId`" />
    <property name="Type" column="`Type`" />
</class>

Example Data

Account
1 - Person - Address
2 - Person - Address

Attribute
1 - Attrib1 - 1 - Account
2 - Attrib2 - 1 - Account
3 - Attrib1 - 2 - Account
4 - Attrib1 - 3 - Event
5 - Attrib1 - 4 - Location

Sample of Existing Code

ICriteria crit = session.CreateCriteria(typeof(Account));
crit.Add(Restrictions.Eq("Name", "Some"););

I would like to add the following to the where clause.

AccountId IN (SELECT LinkId FROM Attribute WHERE Name = 'Attrib1')
+2  A: 

Why aren't you using an any type mapping for this? it does exactly this: referencing by a primary key and type name...

There might be some mistakes in the following piece of code, but it looks something like this:

DetachedCriteria subquery = DetachedCriteria.For<Attribute>()
  .Add(Projections.Property("LinkId"))
  .Add(Restrictions.Eq("Name", "Attrib1"))
  .Add(Restrictions.Eq("Type", typeof(Account)));


ICriteria crit = session.CreateCriteria(typeof(Account));
  .Add(Restrictions.Eq("Name", "Some"))
  .Add(Subqueries.PropertyIn("id", subquery));
Stefan Steinegger
.Add(Subqueries.PropertyIn(expression.PropertyName, criteria)) was the correct syntax on that item. Thanks.
Thad
Yes, this was a typo, I fixed it.
Stefan Steinegger