Mapping a property to a field from another table in NHibernate - nhibernate

consider the following class:
class Order {
int OrderId {get; set;}
int CustomerId {get; set;}
string CustomerName {get; set;}
//other fields go here
}
which is mapped to Orders table. Is it possible to map the property CustomerName to the Customers table through the foreign key relation?

Yes, you can use the join mapping element for this. Another option is to map a view instead of a table. But if possible you should take the object-oriented approach and map the many-to-many relationship between Order and Customer.

I strongly suggest you don't use <join/> for this. Although it would accomplish what you requested, it creates other problems.
Instead, Order should have a relationship with Customer. You can then project the name if you want, although it's easier to just use order.Customer.Name.
So, it boils down to this:
1) Add Customer property to Order
public virtual Customer Customer { get; set; }
2) Map the property (in the example, CustomerId is the name of the FK column)
<many-to-one name="Customer" column="CustomerId"/>
3) If you specifically want to have a CustomerName property, project it from Customer:
public virtual string CustomerName { get { return Customer.Name; } }

Related

Can we make Entity Framework create simpler sql?

We're trying to use Entity Framework Code First (5.0) on a legacy database, where we have some problems with a common pattern involving join tables.
For example, a Customer can have multiple Addresses, but the Address table is also used for other types of addresses so there is a join table to link a customer with it's addresses:
Customer -> CustomerAddress -> Address.
The join table CustomerAdress ha a customer-Id and an address-Id.
In our model we only have a Customer class and an Address class, simplified like this:
public class Customer
{
public long Id { get; set; }
public IList<Address> Addresses { get; set; }
}
public class Address
{
public long Id { get; set; }
}
We set up the mapping in OnModelCreating with code like this:
modelBuilder.Entity<Customer>()
.HasMany(o => o.Addresses)
.WithMany()
.Map(m =>
{
m.ToTable("CustomerAddress");
m.MapLeftKey("CustomerId");
m.MapRightKey("AddressId");
});
Everything works fine but when we try to do queries on Customer that Include() Addresses the resulting sql looks very complex with a select from a select with multiple joins, and after adding another relation like this the amount of sql kind of explodes.
If hand-coding the sql for this relationship I would use a left outer join from Customer to CustomerAddress and then a join from CustomerAddress to Address.
Is there any way we could make Entity Framework create a simpler sql-statement for this example?

NHibernate - criteria to search hierarchical data efficiently

Let's say we have an object model like this:
public class Category
{
public virtual Category Parent { get; set; }
public virtual string Name { get; set; }
public virtual ISet<Category> Children { get; protected set; }
}
public class Product
{
public virtual string Name { get; set; }
public virtual Category Category { get; set; }
public virtual decimal Price { get; set; }
}
On the database side, the relationship would be accomplished through a many-to-many relationship table, so the data schema would be something like this:
Category
=================
Id int PK
Name varchar(50)
Parent_Id int FK
Product
=================
Id int PK
Name varchar(50)
Price money
ProductToCategory
=================
Product_Id int PK
Category_Id int PK
Now let's assume in the tree of categories is a branch that looks like this:
Food
Nut
Cashew
Peanut
Pecan
Bread
Rye
Wheat
White
Assuming we have products with potentially only one sub-category assigned, is it possible to construct a Criteria that would return all products with a category of Food with a single hit to the database and without using a CTE?
Or, given that there won't be an abundance of categories, would it be better to load the full category map into memory and construct the criteria such that it searches for products where Category_Id in (...) and the list is constructed off the in-memory tree?
You'll have to use a CTE to do this. I can't think of a single SQL query that would load all products of a hierarchical category without using, let alone getting NHibernate to do it for you.
Or, given that there won't be an abundance of categories, would it be better to load the full category map into memory and construct the criteria such that it searches for products where Category_Id in (...) and the list is constructed off the in-memory tree?
Yes. If there isn't much data and this is an option, it's the simplest, fastest, low-maintenance, least complex way of doing it.

Nhibernate wrapper query

I want to achieve following thing in Nhibernate, I have SQL query like this
select
rs.firstname, rs.lastname, COUNT(rs.id)
from
(select firstname, lastname, (select name from users where userid = '12345') as id
from person p) rs
group by rs.firstname, rs.lastname
How can i achieve this in Nhibernate? Any pointers will help.
#gdoron is partially correct, You have two options, a) use Session.CreateSqlQuery or b) use a named query which IMO is probably your best option.
In your XML mappings:-
<sql-query name="GetNameAndCount">
<![CDATA[
select
rs.Firstname, rs.Lastname, COUNT(rs.id) CountOf
from
(select firstname, lastname, (select name from users where userid = :id) as id
from person p) rs
group by rs.firstname, rs.lastname
]]>
</sql-query>
and to retreive the data
var results = Session
.GetNamedQuery("GetNameAndCount")
.SetInt32("id", id)
.SetResultTransformer(new AliasToBeanResultTransformer(typeof(NameCountDto)));
return results.List<NameCountDto>();
and your DTO would look like
class NameCountDto {
public virtual string Firstname { get; set;}
public virtual string Lastname { get; set;}
public virtual int CountOf { get; set;}
}
Be warned the column names in your query and your property names case must match.
You could also most likely solve this using HQL, Criteria or QueryOver (I think*) but we would need to see your class and mappings.

How to query Oracle database with NHibernate?

Help me translate this into proper NHibernate...
I have an Oracle database with 2 tables:
Employees:
Id (unique id)
FirstName (string)
LastName (string)
Location (string)
Locations:
Name (string)
Address (string)
As you can see the Employees table has a unique id, but the Locations table has no id whatsoever. The Name field is a regular field and is not unique.
In Oracle SQL I can run the following query:
SELECT *
FROM Employees e
LEFT OUTER JOIN Locations l
ON e.Location = l.Name
WHERE e.Id = 42
The location where the employee 42 is, has 2 rows in the Locations table, so this query returns 2 rows, one for each location found for employee 42.
Well, I can't figure out how to translate this into an NHibernate mapping + query (I use Fluent NHibernate). I tend to think that I should map Employees.Location as a Reference to Locations.Name, and so when running my HQL query it should return 2 objects, but NHibernate wouldn't let me retrieve a list from a Reference. So I tried HasMany but it doesn't work either, because NHibernate wants a field in Locations referring back to Employees, which kinda makes sense.
My HQL query looks like this:
select e
from Employees e
left join e.Locations l
where e.SGId like :sgId
Why can I do this in regular SQL and not in NHibernate?
Thanks.
I found the solution, you have to use HasMany(x => x.Locations) in conjunction with .PropertyRef("Location") so that hibernate knows that the field in Employee to be used for the join should be Location (and not the id of employee as is the default).
class Employee
{
public virtual int Id {get;set}
public virtual string FirstName {get;set;}
public virtual string LastName {get;set;}
public virtual string Location {get;set;}
public virtual IList<Location> Locations {get;set;}
}
class EmployeeMapping : ClassMap<Employee>
{
public EmployeeMapping()
{
Id(x=>x.Id);
Map(x=>x.FirstName);
Map(x=>x.LastName);
Map(x=>x.Location);
HasMany<Location>(x => x.Locations)
.PropertyRef("Location")
.KeyColumn("Name");
}
}
Also I found a few flaws in my approach due mainly to the weird legacy database I'm working with. That doesn't change the solution but I want to add that if one of the tables you're dealing with doesn't have unique ids, you're in trouble. Hibernate needs a unique id, so in my case I had to come up with a composite id made from multiple fields in order to make it unique. This is another debate but I wanted to mention it here to help whoever is researching this topic in the future.
For you mapping you need to use a collection/array/list/set object and a HasMany on your employees mapping for the location if it is going to return 2 locations for the one employee
class Employee
{
public virtual int Id {get;set}
public virtual string FirstName {get;set;}
public virtual string LastName {get;set;}
public virtual IList<Location> Location {get;set;}
}
class EmployeeMapping : ClassMap<Employee>
{
public EmployeeMapping()
{
Id(x=>x.Id);
Map(x=>x.FirstName);
Map(x=>x.LastName);
HasMany<Location>(x => x.Location)
.KeyColumn("Name")
.PropertyRef("Location")
.LazyLoad();
}
}

How to convert SQL aggregate query into NHibernate Criteria Query

I'm new to Criteria API in NHibernate. Can someone generate this piece of SQL using Criteria API in NHibernate?
select count(*)
from result where Student_id
in(
SELECT s.Student_id
from Department as d
JOIN Student s ON d.Dept_id=s.Dept_id
where d.Dept_id=2
)
and how to proceed through the Criteria API in NHibernate. P.S I don't want to use HQL so without HQL is it possible to generate this kind of sql in nhibernate?
You can use linq-2-nhibernate as well.
Given the following class structure:
public class Result{
public virtual Student Student {get; set;}
}
public class Student{
public virtual Department Department {get; set;}
public virtual int Id { get; set;}
}
public virtual Department {
public virtual int Id {get; set;}
public virtual IList<Student> Students {get; set;}
}
Here is your query using the Criteria API:
var studentidquery = DetachedCriteria.For<Student>()
.Add(Restrictions.Eq("Department.Id"),2)
.SetProjection(Projections.Property("Id"));
var count = session.CreateCriteria<Result>()
.Add(Subqueries.PropertyIn("StudentId", studentidquery))
.UniqueResult<int>();
Using the QueryOver API it would look like this:
var studentidquery = QueryOver.Of<Student>()
.Where(x=>x.Department.Id==2)
.Select(x=>x.Id);
var count = session.QueryOver<Result>()
.WithSubquery.WhereProperty(x => x.Id).In(studentidquery)
.Select(Projections.Count<Result>(r=>r.Id))
.UniqueResult<int>();
Also I don't think you need the join to Department in your SQL query as you already have DepartmentId as a foreign key in the Student table. No sense in joining to extra tables for no good reason.