Using NHibernate to report a table with two sums - nhibernate

I have three tables: People, Purchases, Payments with 1-to-many relationships between People and Purchases, and People and Payments.
I want to generate a report of People showing the sum of their Purchases and Payments.
I can easily generate a report for all people showing the sum of the payments or purchases, vis:
var query =
DetachedCriteria.For<People>("People")
.CreateAlias("Payments", "paymentsMade");
query.SetProjection(Projections.ProjectionList()
.Add(Projections.GroupProperty("Id"), "Id")
.Add(Projections.Sum("paymentsMade.Amount"), "TotalPayments")
Can I do this in a single query in NHibernate? Either using the criteria API (preferred) or HQL.

Try something like this:
var query = #"select
(select sum(pu.Amount) from Purchase pu where pu.People.Id = ppl.Id),
(select sum(pa.Amount) from Payments pa where pa.People.Id = ppl.Id)
from People ppl";
var results = session
.CreateQuery(query)
.List();
Or perhaps using ad-hoc mapping:
public class BulkReport
{
public double Purchases { get; set; }
public double Payments { get; set; }
}
var results = session
.CreateQuery(query)
.SetResultTransformer(Transformers.AliasToBean(typeof(BulkReport)))
.List<BulkReport>();
Another option would be using MultiQueries.

Related

Fluent Nhibernate join on non foreign key property

I can't find this anywhere, but it seems pretty trivial. So, please excuse if this is a duplicate.
I have something like:
public class Doctor : Entity
{
...some other properties here...
public virtual string Email { get; set; }
}
public class Lawyer : Entity
{
...some other properties here...
public virtual string Email { get; set; }
}
I want to return all doctors where there is no email match in the Lawyers table like:
select * from Doctors d
where d.Email not in
(select l.Email from Lawyers l where l.Email is not null)
or using a join:
select d.* from Doctors d
left join Lawyers l on l.Email = d.Email
where l.Email is null
The problem is that the Email is of course not set up as a foreign key. I have no mapped property on the Doctor entity that maps to Lawyer.
What I've tried so far:
ICriteria criteria = Session.CreateCriteria(typeof(Doctor))
.CreateAlias("Lawyers.Email", "LawyerEmail", JoinType.LeftOuterJoin)
.Add(Restrictions.IsNull("LawyerEmail"));
return criteria.List<Doctor>();
But, I get a "cannot resolve property Lawyer of MyPlatform.MyNamespace.Doctor" error. Any ideas how to set up my DoctorMap and adjust the criteria tomfoolery to achieve this?
NHibernate for the loss........Entity Framework for the win....
We can achieve that with a feature called subquery:
// a inner SELECT to return all EMAILs from Lawyer table
var subQuery = DetachedCriteria.For<Lawyer>()
.SetProjection(Projections.Property("Email"));
// the root SELECT to get only these Doctors
var criteria = session.CreateCriteria<Doctor>();
// whos email is not in the sub SELECT
criteria.Add(Subqueries.PropertyNotIn("Email", subQuery));
// get first 10
var result = criteria
.SetMaxResults(10)
.SetFirstResult(0) // paging
.List<Doctor>();

How to use ExecuteStoreQuery for fetching data from Multiple tables

My application is in Asp.Net MVC3 coded in C#.Net. My issue is i want to get data from database using SQL query, for that i'm aware that i can use the below technique
Code to get data using ExecuteStoreQuery
var Complete_Data = db.ExecuteStoreQuery<Mytable>("select * from Mytable").ToList();
I have two issues
How to get the data in var Complete_Data when the data is coming from Multiple table (i.e the query has multiple joins).
I will be generating the selecting columns dynamically. The select query columns will generating dynamically.
Below is the sample example
string Field_Formation=string.Empty;
foreach (var item in My_Parameter_Collection_Logic_Variable)
{
Field_Formation+= item.Field_Name + ",";
}
Here My_Parameter_Collection_Logic_Variable is a variable declared in my code that will have a certain collection.
var Complete_Data = db.ExecuteStoreQuery<What_Class_To_Be_Taken_Here>("select" + Field_Formation + " from My_Tables_With_Multiple_Joins").ToList();
Need suggestion, whether it is possible to do such a stuff.
var Complete_Data = db.ExecuteStoreQuery<**What_Class_To_Be_Taken_Here**>
<What_Class_To_Be_Taken_Here> - this class must have properties like your Field_Formation.
For example if your select is:
"SELECT e.idExpense AS ExpenseID, e.idVehicle as VehicleID, d.Date AS Date1 .... join ... where ..."
create class like this:
public class ItemExample
{
private int VehicleID{ get; set; }
private int ExpenseID{ get; set; }
private DateTime? Date1 { get; set; }
}
You can write query using join and get your data from multiple tables.
for eg:-
var Complete_Data = db.ExecuteStoreQuery("select * from Table1 as T1 inner join Table2 as T2 on T1.id=T2.Id").ToList();
You will get all column of all table and then you can access using A.ColumnName or B.ColumnName.

nhibernate manytomany query

I am new to nhibernate and trying to create a query on a database with manytomany links between items and categories.
I have a database with 3 tables : items, categories and a lookup table categoryitem like this:
categorys - primary key categoryId
items - primary key itemId
categoryItem - categoryId column and itemId column
I want a query returning items for a particular category and have tried this and think i am along the right lines:
public IList<Item> GetItemsForCategory(Category category)
{
//detached criteria
DetachedCriteria itemIdsCriteria = DetachedCriteria.For(typeof(Category))
.SetProjection(Projections.Distinct(Projections.Property("Item.Id")))
.Add(Restrictions.Eq("Category.Id", category.Id));
criteria.Add(Subqueries.PropertyIn("Id", itemIdsCriteria));
return criteria.List<Item>() as List<Item>;
}
I only have business objects for category and item.
how do i create a repository method to find items for a particular category?
I assume that your classes look like this:
class Item
{
// id and stuff
IList<Category> Categories { get; private set; }
}
class Category
{
// id and stuff
}
query (HQL)
session.CreateQuery(#"select i
from Item i
inner join i.Categories c
where
c = :category")
.SetEntity("category", category)
Criteria
session
.CreateCriteria(typeof(Item))
.CreateCriteria("Categories", "c")
.Add(Restrictions.Eq("c.Id", category.Id))

How to eager fetch join table collection in Hibernate Native SQL Query?

I have following three database tables
Customer
Product
CustomerProductRelation
Corresponding to these tables, I have two Hibernate POJO's
Product
Customer
One of the member variable is a joinTable:
#JoinTable(name = "CustomerProductRelation", joinColumns = { #JoinColumn(name = "CUSTOMER_ID") }, inverseJoinColumns = { #JoinColumn(name = "PRODUCT_ID") })
private List<Product> products;
Due to some reason, I need to use a native SQL query on Customer table, in that case how do I eager fetch products in my customer list?
I am doing something similar to this:
String queryString = "select c.*,cpr.product_id from Customer c, CustomerProductRelation cpr where c.customer_id = cpr.customer_id";
List list = getSession().createSQLQuery(queryString)
.addEntity("c", Customer.class)
.addJoin("p", "c.products").list();
This does not seem to work. The exception is as follows:
java.lang.NullPointerException at org.hibernate.loader.DefaultEntityAliases.<init>(DefaultEntityAliases.java:37) at org.hibernate.loader.ColumnEntityAliases.<init>(ColumnEntityAliases.java:16) at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.generateCustomReturns(SQ‌​LQueryReturnProcessor.java:264)
Please let me know if anyone knows the solution to this.
Is this what you are seeing? (HHH-2225)

Joining tables in LINQ/SQL

I have below a collection of rows and each row consists of productid, unitid, countryid.
I need to find the details for each row in the corresponding tables (products, units, country)
for product - select product name, updatedby
for unitid - select unit name , updatedby
for countryid - select countryname, uploadby
and returning the rows which has the same format
Id = product id or unitid or countryid
name = proudct name or unit name or countryname
modified = product updatedby or unit updated by or country uploadby
So, in summary -
1. For a Collection of rows
a. use the id to get the extra details from the respective table
b. return the same type of collection for the results
2. do step 1 for
2.a For RegularToys (Run this logic on TableBigA)
2.b For CustomToys(Run this logic on TableB)
3. Return all the rows
by adding 2.a and 2.b
How to write an sql/linq query for this? thanks
If I'm understanding correctly, you want to use a given ID to find either a product, a unit or a country but you're not sure which. If that's the case, then you can build out deferred queries like this to find the given entity:
var prod = from p in db.Products
where p.ProductId = id
select new { Id = p.ProductId, Name = p.ProductName, Modified = p.UpdatedBy };
var unit = from u in db.Units
where p.UnitId = id
select new { Id = u.UnitId, Name = u.UnitName, Modified = p.UpdatedBy };
var ctry = from c in db.Countries
where c.CountryId = id
select new { Id = c.CountryId, Name = c.CountryName, Modified = c.UploadBy };
And then execute the queries until you find an entity that matches (with ?? being the null-coalesce operator that returns the right value if the left result is null).
var res = prod.SingleOrDefault() ??
unit.SingleOrDefault() ??
ctry.SingleOrDefault() ??
new { Id = id, Name = null, Modifed = null };
Without any further details I can't be more specific about the condition below, but I think you are asking for something along these lines. I'm assuming your Id's are int's (but this can be easily changed if not) and you already have an Entity Data Model for the tables you describe.
Create a class for your common data:
class RowDetail
{
public int Id { get; set; }
public string Name { get; set; }
public string Modified { get; set; }
}
Pull the information out of each of the sub tables into a new record:
IEnumerable<RowDetail> products =
from p in db.Products
where <<CONDITION>>
select
new RowDetail()
{
Id = p.ProductId,
Name = p.ProductName,
Modified = p.UpdatedBy
};
IEnumerable<RowDetail> units =
from u in db.Units
where <<CONDITION>>
select
new RowDetail()
{
Id = u.UnitId,
Name = u.UnitName,
Modified = u.UpdatedBy
};
IEnumerable<RowDetail> countries =
from c in db.Countries
where <<CONDITION>>
select
new RowDetail()
{
Id = c.CountryId,
Name = c.CountryName,
Modified = c.UploadBy
};
Finally pull all the records together in a single collection:
IEnumerable<RowDetail> results = products.Union(units).Union(countries);
I'm not sure if this is exactly what you are looking for, so feel free to give feedback and/or more details if further assistance is required.