NHibernate - query specific columns and return distinct records? - nhibernate

I am new to NH.
I have a table in a legacy DB that looks like this:
Id,
CompanyId,
Description,
[LOADS of other columns here]
I would like to return a DISTINCT set of data using NHibernate, selecting only specific columns and using a WHERE statement. The SQL would looks something like this:
SELECT DISTINCT
[table_name].CompanyId,
[table_name].Description
FROM
[table_name]
WHERE
[table_name].CompanyId = 2
Having googled this I came up with:
ProjectionList projections = Projections.ProjectionList();
projections.Add(Projections.Property("CompanyId"), "CompanyId");
projections.Add(Projections.Property("Name"), "SomeName");
var companyDto = session.QueryOver<Company>()
.Where(x => x.CompanyId == 2)
.Select(projections)
.TransformUsing(Transformers.AliasToBean<CompanyDto>())
.List<CompanyDto>();
if (companyDto != null)
Console.WriteLine(string.Format("{0}, {1}", companyDto.CompanyId, companyDto.SomeName));
Where the DTO is:
public class CompanyDto
{
public int CompanyId { get; set; }
public string SomeName { get; set; }
}
And the entity is:
public class Company
{
public virtual int Id { get; private set; }
public virtual int CompanyId { get; set; }
public virtual string Name { get; set; }
}
This does not bring back disinct records. I know that normally I would have to use a different transform (DistinctRootEntity) but I cannot use two transforms. How can I combine all of the things I want, into a single call? It must be possible, its basic SQL ....
I need to:
not use HQL
not bring back all columns for the record
not bring back duplicate rows

there is a Projection for this
var projections = Projections.Distinct(Projections.ProjectionList()
.Add(Projections.Property("CompanyId").As("CompanyId"))
.Add(Projections.Property("Name").As("SomeName"));

Related

Linq and SQL, get only some data

I have two classes like this:
public class Book
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
public int AuthorID { get; set; }
public Author author { get; set; }
}
public class Author
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public string Place { get; set; }
}
They are linked with Foreign Key (of course AuthorID form Book and ID from Author)
I can retrieve data with this query through LINQ:
var _book = context.Book
.Where(x => x.ID == ID_I_Pass_From_FrontEnd)
.Select(x => new Book {
ID = x.ID,
Name = x.Name,
Date = x.Date,
author = new Author {ID = x.author.ID, Name = x.author.Name})
.FirstOrDefault();
In this way I get data without BirthDate and Place from Author and this is my goal.
Unfortunately I need to use SQL because I'm afraid of performances in case number of data will increase. So I started to code and with this:
var sql = string.Format("SELECT * FROM[Book] AS[x] WHERE([x].ID == ({0})), ID_I_Pass_From_FrontEnd");
var result = context.Book.FromSql(sql).Include(x => x.author).FirstOrDefault();
I can retrieve data but with BirthDate and Place. I'd like to avoid these informations.
Of course my real classes are full of columns, what I wrote in this post is just an example.
Other informations:
I'm using AZURE sql as db
I tried, in sql string, to insert INNER JOIN for join with Author table but I got error: "Sequence contains more than one matching element". Probably it is confused about same column name (ID in Book and ID in Author).
How can I achieve, with SQL string, same data of LINQ query? so how can I avoid to get data not useful in that moment?
Use the same projection as in pure LINQ query. There is no difference:
var _book = context.Book.FromSql(sql)
.Select(x => new Book {
ID = x.ID,
Name = x.Name,
Date = x.Date,
author = new Author {ID = x.author.ID, Name = x.author.Name})
.FirstOrDefault();

PetaPoco returning incorrect ID

I have the following model and methods:
[PetaPoco.TableName("TestStep")]
[PetaPoco.PrimaryKey("ID")]
public class TestStep
{
public int ID { get; set; }
public int ParentID { get; set; }
public string Name { get; set; }
public string Details { get; set; }
}
public IEnumerable<TestStep> GetById(int ID)
{
var db = new PetaPoco.Database("TestProcedureDB");
return db.Query<TestStep>(#"SELECT * FROM TESTSTEP TS
INNER JOIN TESTSTEPLINK L ON L.STEPID = TS.ID
WHERE L.TESTID = #0", ID);
}
When the POCO is populated, the ID property value is that of the ID column in the TESTSTEPLINK table. If I change the query to return SELECT TS.* then all is ok. Is this a bug or am I missing something?
PetaPoco will go through all your return columns and map them.
First it will map Id from the table TESTSTEP, then it finds Id again and so it overrides the previously set value.
If you are doing a join like this and only want specific information, you should either only specify the columns you want to return (otherwise you are bringing back more data than needed which is a performance issue)
or do as you did to fix it by using TS.* to ensure only the columns from the first table are mapped.

Workaround for selectmany in ravendb using client api

I have a ravendb class like such:
public class Student
{
public string Id { get; set; }
public string TopLevelProperty { get; set; }
public Dictionary&ltstring, string&gt Attributes { get; set; }
public Dictionary&ltstring,List&ltDictionary&ltstring, string&gt&gt&gt CategoryAttributes { get; set; }
}
and a document like so:
The following linq will not work due to a selectmany:
test = (from student in session.Query()
from eduhistory in student.CategoryAttributes["EducationHistory"]
where eduhistory["StartYear"] == "2009"
select student).ToList();
How can I get all students where StartYear == 2009?
This does it :
test = session.Advanced.LuceneQuery()
.Where("CategoryAttributes.EducationHistory,StartYear:2009")
.ToList();
Notice the comma rather than a dot after EducationHistory. This indicates that we are looking at the list to find a property in one of the items named StartYear.
If I wanted greater than :
test = session.Advanced.LuceneQuery()
.Where("CategoryAttributes.EducationHistory,StartYear:[2009 TO null]")
.ToList();
etc etc.
This should work:
test = (from student in session.Query()
where student.CategoryAttributes["EducationHistory"].Any(edu => edu["StartYear"]== "2009" )
select student).ToList();

NHibernate left join select count in one-to-many relationship

I've been looking for a week after a correct synthax whithout success.
I have 2 classes :
public class ArtworkData
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<CommentData> Comments { get; set; }
}
public class CommentData
{
public virtual Guid Id { get; set; }
public virtual string Text { get; set; }
public virtual ProfileData Profile { get; set; }
public virtual ArtworkData Artwork { get; set; }
public virtual DateTime Created { get; set; }
}
I want to do this query :
SELECT this_.ArtworkId as ArtworkId3_3_,
this_.Name as Name3_3_,
this_.Description as Descript3_3_3_,
FROM Artwork this_
LEFT outer JOIN
(SELECT c.ArtworkIdFk, count(1) Cnt
FROM Comment c
GROUP BY c.ArtworkIdFk) as com
on com.ArtworkIdFk = this_.ArtworkId
ORDER BY 1 desc
But I don't find the way to.
At this moment I just have something like this :
ICriteria c = this.Session.CreateCriteria(typeof(ArtworkData));
if(filter.Category !=null)
{
c.CreateAlias("Categories", "cat")
.Add(Restrictions.Eq("cat.Id", filter.Category.Id));
}
DetachedCriteria crit = DetachedCriteria.For(typeof(CommentData), "comment")
.SetProjection(Projections.ProjectionList()
.Add(Projections.Count("comment.Id").As("cnt"))
.Add(Projections.GroupProperty("comment.Artwork.Id")));
c.Add(Expression.Gt(Projections.SubQuery(crit), 0));
c.AddOrder(Order.Desc(Projections.SubQuery(crit)));
But it's not what I want.
I want to get all Artworks order by the number of comments (but I don't need to get this number).
Please help me! I'm going crazy!
I don't understand what are you trying to do with this weird SQL but if you need to get all Artworks with number of comments you can try this query:
<query name="ArtworkWithCommentsCount">
SELECT artwork.Name, artwork.Comments.size
FROM Artwork artwork
</query>
If you use NHibernate 3 you could use this code:
var artworks = Session.Query<Artwork>().OrderBy(a => Comments.Count);
Or you could use HQL:
Session.CreateQuery("from Artwork a order by size(a.Comments)")
Try Detached Criteria. Take a look at this blogpost.

Problem Using NHibernate Criteria API to Get Specific Results from a Referenced Object

I have an Class that is named Show one of the properties "Country" is a reference to another table.
Show Class
public class Show
{
public virtual int ID { get; set; }
public virtual Country CountryOrigin { get; set; }
public virtual string EnglishName { get; set; }
}
Country Class
public class Country
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
}
I have it all mapped and working, but now I am wanting to get more specific results. I have used the criteria api to get all the data and sort it, but now I only want to get shows based on country name. Here is what I thought would work, but apprently doesn't.
public IList<Show> AllShowsByCountry(string countryName)
{
IList<Show> shows;
shows = _session.CreateCriteria(typeof(Show))
.Add(Restrictions.Eq("CountryOrigin.Name", "China" ))
.AddOrder(Order.Asc("EnglishName"))
.List<Show>();
return shows;
}
I was thinking that the first part of the restriction might work similar to HQL and you can use objects.
1) The question I guess is am I mis-understanding how HQL works or criteria or both?
2) Also how would you do this properly using criteria?
Update
Here is the error I am getting
could not resolve property: CountryOrigin.Name of: Entities.Show
For Criteria, use the following:
_session.CreateCriteria<Show>()
.CreateAlias("CountryOrigin", "country")
.Add(Restrictions.Eq("country.Name", countryName))
.AddOrder(Order.Asc("EnglishName"))
.List<Show>();
Of course HQL is easier when you are not constructing a dynamic query (search):
_session.CreateQuery(
#"
from Show
where CountryOrigin.Name = :countryName
order by EnglishName
")
.SetParameter("countryName", countryName)
.List<Show>();
And Linq always rocks:
_session.Query<Show>()
.Where(s => s.CountryOrigin.Name = countryName)
.OrderBy(s => EnglishName)
.ToList();
(.Query is for NH 3.x; for 2.x use .Linq)