It's very frustrating that you cannot use QBE on associations.
I have a large datatable with about 8 many-to-one columns. There is a a drop-down list for every column to filter the table.
Let's assume the following:
Table User
User { id, UserStatus, UserAuthorization }
I want to use this code:
Criteria crit = getSession().createCriteria(class);
crit.add(Example.create(userObject));
This does not work on the following example userObject
:
User id=1 { UserStatus=Active, UserAuthorization=Admin }
because QBE doesn't support collections.
One way to solve this is to use it this way:
crit.createCriteria("UserStatus").add(Example.create(userStatusObject));
crit.createCriteria("UserAuthorization").add(Example.create(userAuthorizationObject));
My question is how this can be programmed dynamically just with the given User
object. Is there another way than using QBE?
you can combine QBE and normal Expressions to handle the parts QBE doesnt support
Criteria crit = getSession().createCriteria(class);
.add(Example.create(userObject));
.add(Expression.eq("UserStatus", userObject.getUserStatus()));
Here's a generic answer that I found worked for me inside of my repository base, using reflection:
protected T GetByExample(T example)
{
var c = DetachedCriteria.For<T>().Add(Example.Create(example).ExcludeNone());
var props = typeof (T).GetProperties()
.Where(p => p.PropertyType.GetInterfaces().Contains(typeof(IEntityBase)));
foreach (var pInfo in props)
{
c.Add(Restrictions.Eq(pInfo.Name, pInfo.GetValue(example)));
}
return Query(c);
}
Note that all of my entities inherit from IEntityBase, which allowed me to find just those foreign key references from the object properties so I could add them to the criteria. You'll have to provide some way to execute the query (i.e. c.GetExecutableCriteria(Session))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With