How do IN () statements work in NHibernate? (Using Criteria) - c#

I'm trying to create the equivalent of the below using NHibernate. I've done all the mappings using fluent and I can do the basic queries just fine but I have no idea how to do this.
-**Product Table**
Reference
Title
Subjects (Many to Many relationship)
Price
-**Subject table**
SubjectID
Name
-**SubjectToProductMapping Table**
Reference
SubjectID
Now I need to do this:
SELECT *
FROM Product
WHERE Reference IN
(Select Reference FROM SubjectToProductMapping WHERE SubjectID = #SubjectID)
Baring in mind the Product table has been simplified a great deal for the post and that I would prefer to use an IN statement to keep the rest of the query simpler. I would ideally like to create the query using Criteria becuase I will be using Criteria to page the results.
Thanks in advance

Why would you use an in when a join would suffice? provided your Products class has a mapped collection of subjects then you could just use this Criteria
IList<Product> results = session.CreateCriteria(typeof(Product))
.CreateCriteria("Subjects", JoinType.Join)
.Add(Resitctions.Eq(Projections.ID, subjectID))
.List<Product>();

Related

Asp.net/SQL - Retrieving data from multiple tables using foreign keys

I'm new to ASP.NET and SQL, and I'm trying to build a Web Forms project that will basically display data using grids.
I'm using Entity Framework along with a Data Transfer Object and a Data Access Layer for displaying/editing data.
My issue is that I'm not sure what is the best way of retrieving data using foreign keys.
Example:
Table 1 - Products
|(PK) Product ID | Product Name | Country ID(FK)
Table 2 - Countries
|(PK) Country ID | Country Name|
Final Result Should be:
Product ID | Product Name | Country Name|
What's the best way to accomplish that?
Thanks in advance
The best approach is use a projection to do that.
Your code will be similar to the code below:
context.Products.Select(x=>new ProductDto
{
ProductId=x.ProductId,
ProductName=x.Name,
CountryName=x.Country.Name
});
Using projections you will ensure that is retrieving only the necessary data from DB.
Hope this helps!
You can make LINQ query from this one. Better, you create one separate class and retrieve only data which you want.
SQL Query :
SELECT P.ProductID, P.ProductName, C.COuntryName FROM Products P
INNER JOIN ON Countries C ON C.CountryID = P.CountryID
Execute Query using EF :
context.Database.SqlQuery<ProductDTO>(query).ToList();

How do I used Count(*) with DAL2?

I want to get counts for various groupings of data in some of my tables and am not sure if it is possible using DAL2.
I want perform queries such as:
SELECT DISTINCT productType, COUNT(*) FROM Products GROUP BY productType
The information I come across only includes examples that allow the user to specify the WHERE part of the SQL. This example unfortunately skirts right around the WHERE part of the query so I am not sure how I should approach this using DAL2. Is it possible using DAL2 or do I need to query the database another way? If it can be done using DAL2, how do I execute such a query?
The examples showing only the WHERE part mean that PetaPoco fills in the "SELECT * FROM TableName" part for you, but of course you can execute your own sql statement
In your case:
public class ProductCount {
public int ProductType {get; set;}
public int Count {get; set;}
}
var ProductCountList = db.Fetch<ProductCount>(#"SELECT DISTINCT productType,
COUNT(*) as Count
FROM Products
GROUP BY productType");
I can't tell you what is best practice. But I have a SQL server back end and use dal2 with a dnn module. I just created a view in SQL server with my grouping and joins and then mapped that view like a table (use view name instead of table name in the class annotations) with an auto increment of false. Worked for me and I get the benefit of precompiled and non dynamic queries. If you need to generate this dynamically, I am not sure what the best approach is.
I would love to hear from other members about this.

Mapping from relational database

For one to one relationships things are easy.
When it comes to one to many or many to many problems appear...
I am not using an ORM tool now for many reasons and i am wondering when i want to get data whether it is better to reassemble one to many relationship using multiple queries or in code..
For example.. Having a class Category and a class Product...
A product table has a collumn for category id (one category many products).
So for my full catalog is it better to execute 2 queries to get the categories and products i want and then populate for each category its products List ? (It is very easy with LINQ) ..
Or i should call query for each category ? Like select id from products where category_id=5;
Also i dont know how to name the functions like to set whether i want to fetch the other side of the relationship or not..
You should always use the least number of queries possible to retrieve your data. Executing one query per category to load the products is known as the N+1 problem, and can quickly cause a bottleneck in your code.
As far as what to name your methods that specify your fetch plans, name them after what the method actually does, such as IncludeProducts or WithProducts.
If you want to retrieve all categories and all their products, you can either select all categories and then select all products in two queries, or you can select in one query and group.
To use just one query, select an inner join for your two tables
SELECT c.*, p.*
FROM Category c INNER JOIN Product p ON c.CategoryId = p.CategoryId
and then construct business objects from the resulting dataset
result.GroupBy(r => r.CategoryId).Select(group =>
new Category(/* new Category using c.* columns */)
{
Products = /* new list of Products from p.* values */
});
But I have to ask - why aren't you using an ORM?

Perform a Linq Many to Many Query

In SQL I have 2 tables.
Sport Athlete
SportId AthleteId
SportName AthleteName
Their relation is many to many. So there is a third table that join them.
AthleteSport
AthleteId
SprortId
If i create an entity data model using the wizard the third table is disapeared and only creates the 2 main tables with the many to many relation.
how can I perform a query to find out what kind of sports athlete 'A' does? How to change them or add a new sport?
I want to use linq and c#.
Thank you.
In your Sport entity, there will be a so called "navigation property" Athletes that contains all Athletes that belong to that Sport instance.
The same is true the other way around.
Can't you do A.Sports and get that list?

Comparing SQL tables and getting Values using Entity Framework

I have three tables viz: Person(PersonID(INT), Personname(varchar)) , Items(ItemID(INT), Itemname(varchar)) and PersonItemAssoc(PersonItemAssoc(Int), PersonID(INT), ItemID(INT)).
PersonItemAssoc is having many to many association for personid and Itemid.
I want to get way in which if I pass the itemId, I should get all the PersonIds which dont have an association witn this ItemId in the PersonItemAssoc table.
I am using Entity Framework 4.0.
Please suggest a way for implementing this.
var peopleWithoutItem = from p in Context.Person
where !p.PersonItems.Any(pi => pi.Item.ItemId == someItemId);
select p;
Note that if you get rid of PersonItemAssoc(int) and make the PersonItemAssoc PK the compound of PersonID and ItemID then the EF can do People to Items as a many to many, instead of two 1 to many relationships.

Categories