LastIndexOf in RavenDB RQL? - ravendb

I'm searching for a way to do some string manipulation in RQL. I have a string "xxx.yyy.zzz" and I would like to display this zzz. I found substr function but I cannot find something like lastindexof?

You can make a query on a collection and select (create a projection) using javascript, and then use whatever method you like, i.e. lastIndexOf
var query = from user in session.Query<User>()
select new
{
Location = RavenQuery.Raw<int>("user.Name.lastIndexOf('x')");
};
You can create a javascript index and make a query on it
https://ravendb.net/docs/article-page/5.1/Csharp/indexes/javascript-indexes
Use any javascript method when defining your index field property inside the Map method

Related

Convert LinkedHasSet from one type to another

I have a very simple problem, I need to convert a LinkedHashSet that holds one type of object, into another.
So basically what I want to do is something like this(if map could return anything else than TypeB:
LinkedHashSet<TypeA> firstSet
LinkedHashSet<TypeB> secondSet = firstSet.map {
TypeB(firstSet.value1, firstSet.value2)
}
This is mostly written to signalize what I want to achieve, of course it doesn't work. Could someone help me write this in Kotlin?
map returns a List, but you can use mapTo to insert the resulting elements directly into a collection that you provide as its first argument. This collection is also returned so you can assign it to secondSet:
val secondSet: LinkedHashSet<TypeB> = firstSet.mapTo(LinkedHashSet<TypeB>()) {
TypeB(it.value1, it.value2)
}
This is more efficient than using map because it avoids creating an intermediate List to hold the results.

What can I do with the IEnumerable(of T) result except iterate over it?

Ok, I'm new to Linq and I'm using VB.NET. Given a list of objects that has 2 properties called AttributeVariable and AttributeValue, I want to select the AttributeValue for the first item in a collection that has a specific AttributeVariable value. This is my start:
Dim query = From c In items
Where c.AttributeVariable = "thename"
Select c.AttributeValue
Cool, it works and I can for each over the query results and write out the result.
Since c.AttributeValue is a String, what is the simplest way to assign the first item in the list (there is only one) to a string variable?
How about FirstOrDefault? (There is also SingleOrDefault and overloads that take default values; consult the documentation.)
Returns the first element of a sequence, or a default value if the sequence contains no elements.
Then:
Dim attribute = (From c In items
Where c.AttributeVariable = "thename"
Select c.AttributeValue).FirstOrDefault()
The key to this is the attribute value (a String) is selected before the FirstOrDefault - thus the resulting type of the expression is a String.
In any case, while I don't believe it is possible to do this with just query syntax, that does not pose an issue because the (query) returns an IEnumerable which can then be used with a "normal" Enumerable extension method as shown.

Restricting an NHibernate query using ICriteria according to an enumeration of enums

I have an entity, with a field of type enum, that is persisted as an integer in my database.
When retrieving objects from the database using ICriteria, I wish to restrict the results to those with the field being a member of a collection of enum values. Does Restrictions.In work with a collection of enums?
The following does not work. Do I have to perform something like type-casting at the "restrictions.in" part of the query?
var myEnumCollection = new MyEnum[] { MyEnum.One };
return FindAll<MyType>(Restrictions.In("EnumProperty", myEnumCollection));
FindAll is a method encapsulating
criteria.GetExecutableCriteria(Session).List<MyType>()
My initial guess would be that you'll need to compare against the integer values of the enum members (assuming that you're mapping the enum as an integer); so something like:
var myEnumCollection = new int[] { MyEnum.One };
return FindAll<MyType>(Restrictions.In("EnumProperty", myEnumCollection));
May be the solution that you're after. If you update your post with further details (mapping of the enum member and the sql being generated by the query), I may be able to provide further assistance.

Specifying properties to be updated in linq query

I want to be able to specify the properties to get populated/updated in the linq expression.
Something in the following fashion:
Proxy.UpdateEmployee(List<string> propertiesNames)
Proxy.GetEmployee() //inside the method populate only certain properties
The return values must be of known type(no anonymous types accepted).
DLINQ enable to select by specifying properties' names but the result is IQueryable interface and I'm unable to AsEnumerable() it in order to build the known type query afterwards.
You have to use reflection to modify instance properties by name.
So wherever you're updating your object with LINQ you need to do something like this:
foreach (string propName in propertiesNames)
{
PropertyInfo prop = this.GetType().GetProperty(propName);
prop.SetValue(valueForProp);
}

How do I run an HqlBasedQuery that returns an unmapped list of objects using nHibernate?

I want to run a query against two tables (which happen to be mapped in ActiveRecord). The query returns a result list that cannot be mapped to an ActiveRecord object (as it is custom aggregate information).
For instance
Dim query_str as string = "Select distinct d.ID, (select count(1) as exp from Sales_Leads where date_created <= :todays_date) as NbrLeads from Dealer d"
Dim q As Queries.HqlBasedQuery = New Queries.HqlBasedQuery(GetType(ICollection), query_str)
q.SetParameter("todays_date", DateTime.Today)
Dim i As ICollection = ActiveRecordMediator.ExecuteQuery(q)
What I'm looking for is simple execution of SQL, without an ActiveRecord object returned.
So, ideally, I'd be able to look at i("NbrResults") for each item in the collection.
The error I am getting is:
You have accessed an ActiveRecord
class that wasn't properly
initialized. The only explanation is
that the call to
ActiveRecordStarter.Initialize()
didn't include
System.Collections.ICollection class
Well, this was asked a long time ago but I have a working answer.
public static IList<T> ExecuteQuery<T>(HqlBasedQuery query)
where T : new()
{
query.SetResultTransformer(new NHibernate.Transform.AliasToBeanResultTransformer(typeof(T)));
var results = (ArrayList)ActiveRecordMediator.ExecuteQuery(query);
List<T> list = new List<T>(results.Count);
for (int i = 0; i < results.Count; i++)
{
list.Add((T)results[i]);
}
return list;
}
This will give you back results of type T. Type T can be anything you want. Type T needs a no argument constructor and it needs public fields or properties that match the column names or aliases in the query you build.
We do this all the time. Particularly when you want to use aggregate function in HQL to produce aggregate data.
A companion function will allow you to just pass in your query as a string as well as any positional parameters you might have:
public static IList<T> ExecuteQuery<T, U>(string hqlQuery, params object[] parameters)
where T : new()
{
return ExecuteQuery<T>(new HqlBasedQuery(typeof(U), hqlQuery, parameters));
}
Type U is any type that is a valid ActiveRecord type. It doesn't even have to be one of the types you are referencing. If you want you could replace it will some type you know is gonna be valid int he session and ditch the extra parameter.
Here was my final solution:
Dim query_str As String = "SELECT DISTINCT d.ID, count( l ) from LEAD as l join l.Dealer as d where l.DateCreated >= DATEADD(day, -30, :todays_date) GROUP BY d.ID"
Then obtain the active record session (or NHibernate, still don't even know what is returned here):
Dim sess As ISession = activerecordmediator.GetSessionFactoryHolder().CreateSession(GetType(ActiveRecordBase))
Dim q As NHibernate.IQuery = sess.CreateQuery(query_str)
q.SetParameter("todays_date", DateTime.Today)
Dim i As IList = q.List() ' get results
In the .aspx page, the result can be accessed in a GridView like so:
You're stepping outside the NHibernate paradigm to call down to SQL, which is somewhat against the spirit of ORM. It's not 'bad' per-se, but I'd certainly avoid breaking the abstraction if I could to try to maintain a looser coupling.
You can do what you want with a straight HQL query, which will return a collection of tuples containing the results of your query. I explained how to do this here
Custom query with Castle ActiveRecord
which you might want to have a look at. Even though you must specify a type when you new an HQLBasedQuery, NH is smart enough to know that if you don't select a type instance it should assemble a result-set based on object tuples.
(IMNSHO it's still a bit non-pure - I'd be tempted to try to model this relationship as an object and map it accordingly, but then I'd have to bash the DB into shape to suit the object model and that's not going to fly in all cases.)