How to write HQL queries using NHibernate. What namespaces will I have to included so that everything works fine. Actually I have 2 tables Ticket and Trip and I wanta count of all the records in Trip that do not have a corresponding entry in Ticket. There is a tid field in ticket that refrences Trip id. Can anybody please explain me from start how will I write a NHibernate HQL query for this?
You don't need any special namespaces to use HQL. Just create a simple NHibernate project and you can start writing HQL right away.
Here is an example from the new NHibernate 3.0 Cookbook and you should also check the Nhibernate in Action book which has a more elaborate examples on HQL.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
namespace ExecutableHQL
{
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
var nhConfig = new Configuration().Configure();
var sessionFactory = nhConfig.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
int count = (int) session.CreateQuery("select count(*) from Trip").UniqueResult();
tx.Commit();
}
}
}
}
}
[HttpGet]
public int GetCount()
{
var myQuery = session.CreateQuery(#"
select COUNT(*) from Table as t where
t.Id = :Id");
myQuery.SetParameter("Id", this.Id);
int count = Convert.ToInt32(myQuery.UniqueResult());
return count;
}
Related
I'm doing some tests to take a project. I have been working with ASP.NET Core MVC and Entity Framework relatively recently. I have a simple database in SQL Server to prove how it is:
In the test project I have a controller TestController; the code is this:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using WEBAPPHTTP.Models;
namespace WEBAPPHTTP.Controllers
{
[Route ("api/controller[]")]
public class TestController: Controller
{
[HttpGet("/api/values")]
public IEnumerable<string> Get()
{
using (TareasContext db = new TareasContext())
{
var listar = db.Tareas;
var n = listar.Count();
string[] array = new string[n+1];
int i = 0;
foreach (var otareas in listar)
{
array[i] = otareas.Tarea.ToString();
i = i++;
}
return array;
}
}
}
}
Obviously I'm doing something wrong but the output is this:
in localhost/api/values:
["ahora",null,null,null,null]
It only shows me the last record of the database followed by a few NULL, this test the idea is that all the results are loaded in the array.
I'm sure it's a very early mistake, I hope you can guide me.
I dont know what you want to do after this, but if you just want to list out your items, you should be able to do something like this:
using (TareasContext db = new TareasContext())
{
return db.Tareas.ToList();
}
That will give you the full list with all items in it with all properties, if you want just a part of your properties I would suggest to do a .Select as well.
Remember to do a where as well so you dont always return the full list (if it gets enourmus big)
Peace!
You code is not efficient. This is the much cleaner version that does the same:
using (TareasContext db = new TareasContext())
{
var result = db.Tareas.Select(x => x.Tarea).ToList();
return result;
}
As I see the Tarea column is of varchar or nvarchar type. So, you don't need to cast it to string.
Is is it possible to execute multiple queries using SqlKata at the same time.
Currently I have the following code:
var latestUsersQuery = db.Query("tbl_users").Where("created_at", ">", from);
var activitiesQuery = db.Query("tbl_activities").WhereIn("user_id", latestUsersQuery.Clone());
and I am querying each one alone.
var latestUsers = latestUsersQuery.Get();
var activities = activitiesQuery().Get();
I am wondering if there is a way to execute both queries at the same time.
// for example something like this
var results = db.GetAll(latestUsersQuery, activitiesQuery);
Thanks.
Late to the game on this, but you could extend SqlKata's QueryFactory class similar to how they write the other methods; using extension methods.
using SqlKata;
using SqlKata.Execution;
using System.Collections.Generic;
using System.Linq;
// ...
public static class QueryFactoryExtensions
{
public static IEnumerable<IEnumerable<T>> GetAll<T>(this QueryFactory db, params Query[] queries)
{
return queries.Select(q =>
{
return SqlKata.Execution.QueryFactoryExtensions.Get<T>(db, q);
});
}
public static IEnumerable<IEnumerable<dynamic>> GetAll(this QueryFactory db, params Query[] queries)
{
return GetAll<dynamic>(db, queries);
}
}
The usage would look like:
var query1 = new Query();
var query2 = new Query();
var results = db.GetAll(query1, query2)
From there you could: enumerate over it, cast to an array and access by index, etc.
Bear in mind here, this is not sending one query to the database as mentioned in the comments of the OP. If performance is truly what you're after, then you might look at using the Dapper extension method QueryMultiple instead of Query (which is what SqlKata is calling on the Get() methods). I'm not familiar enough with the underlying magic that Dapper is doing to be able to confidently give you direction. Another possiblity for you could be to add extensions for GetAsync instead of Get. This may be better suited to your needs.
All of that said, at minimum I hope that this provides you with some direction in which to make a decision or potentially benchmark performance.
I am using EF 6 & Visual Studio 13 free community.
I am using database-first approach in my current project.
I created A SQL Server DB project and added it to my project to work with EF
I created tables & some stored procedures. After I added the db to my project it created a class procedure_name_Result and i need to use linq queries in my project but I don't know how to call it in the query, or if it will even recognize it as I can't see it in the uploaded db
EDIT Thanks to you both answers i was able to know how to probably call in a Linq query
var query = from X where Y
select new {
elemnt,
var_inside_query = DB.procedure_name(#params)
};
I use Northwind database as sample project.
using System;
using System.Collections.Generic;
using System.Linq;
namespace EF_SP
{
class Program
{
static void Main(string[] args)
{
using (var context = new NorthwindEntities())
{
var results = context.GetSalesByCategory("Seafood", "1998");
foreach (var result in results)
Console.WriteLine("{0} {1}", result.ProductName, result.TotalPurchase);
}
Console.WriteLine("Press any key. . .");
Console.ReadKey(true);
}
}
}
i try this code and It is giving me the error on the 'where'
i verify: using system.linq; and using System.Data.Entity but not fixed(i work with visual studio 2012 ultimate and sql server 2008 r2)
code:
public static int updatecondidate(int condidateID, condidate_table updatedcondidateData)
{ int rowAffected = 0;
using (EmployeementSystemEntities DB = new EmployeementSystemEntities())
{
//select condidate for update
condidate_table condidateforupdate = (from anything in DB.condidate_table
where anything.condidate_id == condidateID
select anything).FirstOrDefault();
condidateforupdate.condidate_name = updatedcondidateData.condidate_name;
condidateforupdate.condidate_phone = updatedcondidateData.condidate_phone;
condidateforupdate.condidate_email = updatedcondidateData.condidate_email;
condidateforupdate.condidate_pic = updatedcondidateData.condidate_pic;
rowAffected = DB.SaveChanges();
}
return rowAffected;
}
the same error here on "Select"
//select all condidate
public static List<condidate_table> SelectAllCondidate()
{
using (EmployeementSystemEntities DB = new EmployeementSystemEntities())
{
List<condidate_table> AllCondidate = (from anything in DB.condidate_table
select anything).ToList<condidate_table>();
return AllCondidate;
}
}
public List<ISSUES> ListIssues()
{
List<ISSUES> list = new List<ISSUES>();
using (FTUEntities1 db = new FTUEntities1())
{
list = db.ISSUES.Include(a => a.CLIENTS).ToList();
return list;
}
}
In my case I missed this:
using System.Data.Entity;
where anything.condidate_id = condidateID should be where anything.condidate_id == condidateID (note the double equals).
Here is a general list of issues, that I can find, that people are reporting has caused this same error for them. I will update it as I find more.
Query Syntax
using = instead of == in the where clause
referencing variables in the query statement that have not been declared
using incorrect punctuation for variable names (goes to the second point)
calling a method inside the query and forgetting the parentheses, e.g. c.FullNameReverse instead of c.FullNameReverse()
missing conditional operators (&&, ||, etc...) in the where clause when creating compound predicates
referencing static properties as if they were instance properties
referencing object properties that do not exist
Missing using statements
using System.Linq
using System.Data.Entity
I am still a beginner at writing C# and SQL and was wondering if someone could help me with this basic question. I have looked all over the internet and am still stuck.
I am trying to write a WCF service to access my database. I only need one method:
public PathDto GetPath(string src, string trg)
{
using (var context = new PathsEntities())
{
var p = (
from a
in context.src
where a.Target = trg
select a).Distance, Path;
}
}
where the parameter src is the table name, and the string trg is the entity's primary key.
Visual studio gives me the error: ...pathsService does not contain a definition for src because it is trying to look up the table "src" and not the string contained in the variable.
How can I use my parameter in the lookup statement?
I am going to assume you are using DbContext EF5.0 stuff
public PathDto GetPath(string tableType, string id)
{
using (var context = new PathsEntities())
{
var type = Type.GetType(tableType);
var p = context.Set(type).Find(id);
return (PathDto)p;
}
}
Seems you DON'T use EF 5.0 and have only got EF 4.0 and are using ObjectContext. Try this...no idea if it works since I don't really use EF 4.0. Alternatively download EF 5.0
public PathDto GetPath(string tableType, string id)
{
using (var context = new PathsEntities())
{
var type = Type.GetType(tableType);
var p = context.GetObjectByKey(new EntityKey(tableType, "id", id));
return (PathDto)p;
}
}