Easiest way to check record is exist or not in Linq to Entity Query - sql

in store procedure we can check record is exist or not using following query for fast performance
if EXISTS ( Select 1 from Table_Name where id=#id )
But what about Linq query.
right now i have to store whole data in object like this
UserDetail _U=db.UserDetails.where(x=>x.id==1).FirstOrDefault();
Any Solution?

Use Linq's Any ie bool exist = db.UserDetails.Any(x => x.id == 1);
if(db.UserDetails.Any(x => x.id == 1)) {
var userDetail = db.UserDetails.FirstOrDefault(x => x.id == 1);
}

bool exist = db.UserDetails.Where(x=>x.id==1).Any();
if(exist){
//your-code
}else{
//your-code
}

Just check
if(_U == null)
This way you will get what you want in single query and you not need to execute addition query like
db.UserDetails.Any(x => x.id == 1)

I think, it does not require to fire two query. It can be accomplish by single query.
UserDetails objUserDetails =db.UserDetails.FirstOrDefault(x => x.id == 1);
if(objUserDetails==null)
{
// Do something
}
else
{
// do something with objUserDetails
}

var qry = db.User_Detail.Where(x => x.User_Id == 1).FirstOrDefault();
if(qry !=null)
{
// Do something
}
else
{
return false;
}
Try This...

Related

How to combine IQueryable records in .net Core 6 Web API

I'm using .net Core 6 web API, and I've this case where I need to loop through multiple object, and each has a IQueryable result.
Then all results need to be grouped in one query. Finally the the result will be sent as paginated list.
Here's more details in the code, I will get list of ObjectA from db:
var query = _context.ObjectA.AsQueryable();
Now I need to get list of User. For some reason the users will have multiple records with their username, so each record represent a role:
var rolesFromDb = await _context.User.Include(x => x.Role).Where(x => x.Username == "user").ToListAsync();
Now I need to loop through dynamic roles and filter the query. I have 2 (or more) conditions, the the code will look like this:
if (rolesFromDb.Count != 0)
{
var result = new List<ObjectA>();
foreach (var item in rolesFromDb)
{
if (item.Role.Level == 1)
{
var condition1 = query.Where(x => x.Level == 1);
result.AddRange(condition1);
continue;
}
if (item.Role.Level == 2)
{
var condition2 = query.Where(x => x.Level == 2);
result.AddRange(condition2);
continue;
}
}
query = result; // I need to do something like this, this is not the way to do ofc
}
After this loop, I've a search filter that depends on this query.
In general, my main issue is I'm not able to make query = all filtered queries.
Thank you.

optimize a SQL query for a couchdb view

How to optimize this SQL query for a couchdb view ?
SELECT * FROM db WHERE user = '$userid' OR userFollowed = '$userid'
The couchdb database contains this structure of documents:
_id
user
userFollowed
This because a user can follows another and viceversa and my scope is to get all followers of user A that this user which follows it turn, for example:
A follows B
B follows A
In this example I need to get B, enstabilishing that both users are followers... I know it's complex to explain and understand but I'll try with the things I'm doing with node.js and cradle.
The view map:
function (doc) {
emit(doc.user, doc.userFollowed)
}
The node.js code:
db.view("followers/getFollowers", function(err, resp) {
if (!err) {
var followers = [];
resp.forEach(function(key, value, id) {
var bothFollow = false;
if (key == userID) {
if (followers.indexOf(value) == -1) {
resp.forEach(function(key, value, id) {
if (value == userID)
bothFollow = true;
});
if (bothFollow)
followers.push(value);
}
} else if (value == userID) {
if (followers.indexOf(key) == -1) {
resp.forEach(function(key, value, id) {
if (key == userID)
bothFollow = true;
});
if (bothFollow)
followers.push(key);
}
}
});
console.log(followers);
}
});
So in the code first I check if the A or B values corrispondes to the other user, then check with another loop if there is a relationship putting the follower in the list
All this code works but I don't think that's the correct procedure and maybe I'm wrong anything :( can you help me please ?
It is easier to emit both users in the view function:
function (doc) {
emit(doc.user, null);
emit(doc.userFollowed, null);
}
Than you can just call the view and will get a plain list:
http://localhost:5984/db/_design/app/_view/followers?include_docs=true

WPF application Linq to sql getting data

I'm making a WPF application with a datagrid that displays some sql data.
Now i'm making a search field but that doesn't seem to work:
Contactpersoon is an nvarchar
bedrijf is an nvarchar
but
LeverancierPK is an INT
How can I combinate that in my search?
If i convert LeverancierPK to string, then I can use Contains but that gives me an error
//Inisiatie
PRCEntities vPRCEntities = new PRCEntities();
var vFound = from a in vPRCEntities.tblLeveranciers
where ((((a.LeverancierPK).ToString()).Contains(vWoord)) ||
(a.Contactpersoon.Contains(vWoord)) ||
(a.Bedrijf.Contains(vWoord)))
orderby a.LeverancierPK
select a;
myDataGrid_Leveranciers.ItemsSource = vFound;
Thanks
If you don't care about pulling all records back from the DB (which in your answer you pulled everything back), then you can just do a .ToList() before the where clause.
var vFound = vPRCEntities.tblLeveranciers.ToList()
.Where(a => a.LeverancierPK.ToString().Contains(vWoord)) ||
a.Contactpersoon.Contains(vWoord) ||
a.Bedrijf.Contains(vWoord))
.OrderBy(a.LeverancierPK);
This code can do what I was looking for but I think it could be alot shorter.
PRCEntities vPRCEntities = new PRCEntities();
var vFound = from a in vPRCEntities.tblLeveranciers
orderby a.LeverancierPK
select a;
myDataGrid_Leveranciers.ItemsSource = null;
myDataGrid_Leveranciers.Items.Clear();
foreach (var item in vFound)
{
if (item.Bedrijf.Contains(vWoord))
{
myDataGrid_Leveranciers.Items.Add(item);
}
else
{
if (item.LeverancierPK.ToString().Contains(vWoord))
{
myDataGrid_Leveranciers.Items.Add(item);
}
else
{
if (item.Contactpersoon != null)
{
if (item.Contactpersoon.Contains(vWoord))
{
myDataGrid_Leveranciers.Items.Add(item);
}
}
}
}
}

How to create a Dynamic Query when there's a condition that won't use all fields in the where section with LinQ

I am using a Data Entity from the db, and a Domain Service.
I am using .net's generated code for the simple queries, like this
public IQueryable<employee> GetEmployeesByLocale(int localeID)
{
return ObjectContext.employees.Where(e => e.Locale_ID == localeID);
}
Now, I need to change the .Where section accordingly, so:
if (localeID > 0)
{
['Where' should be like .Where(e => e.Locale_ID == localeID)];
}
if (projectID > 0)
{
[IF localeID == 0, 'Where' should be like .Where(e => e.Project_ID == projectID)
Else if localeID > 0, Where should use both, sort of .Where(e => e.Locale_ID == localeID && e.Project_ID == projectID)];
}
and so on with other variables.
There are many possible combinations , which is why I was trying to use the overload for .Where(string, parameter[])
string q = string.Empty;
if (localeID > 0)
{
q = "Locale_ID = " + localeID.ToString();
}
if (projectID > 0)
{
q = q == string.Empty ? "Project_ID = " + projectID.ToString() : q + " and " + "Project_ID = " + projectID.ToString();
}
... (for other variables and fields)
...
System.Data.Objects.ObjectParameter[] param = new System.Data.Objects.ObjectParameter[1];
param[0] = new System.Data.Objects.ObjectParameter("param", 1);
return ObjectContext.employees.Where(q, param);
However, this only gives an error, because then all the fieldnames are supposedly out-of-scope/non-existing. Even if use employees.[field_name] in the string, they "don't exist"
Does anyone know of a way to use conditionals inside the .Where part of the query? Or how to create some var or object containing my query so I can just parse it?
You can use
IQueryable<Employee> emp = ObjectContext.employees;
if (localeID > 0)
emp=emp.Where(e => e.Locale_ID == localeID).AsQueryable();
if (projectID > 0)
emp=emp.Where(e => e.Project_ID == projectID).AsQueryable();
This will concatenate the where clauses

Check if object exists in database without loading object with NHibernate

Is there a way in NHibernate to check if an object exists in the database without having to get/load the object?
You could use one of the following 3 queries (or you could use Criteria API Projections.RowCountInt64() from David answer):
bool exist = session.Query<Employee>()
.Any(x => x.EmployeeID == 1);
bool exist = session.QueryOver<Employee>()
.Where(x => x.EmployeeID == 1)
.RowCount() > 0;
bool exist = session.Query<Employee>()
.Count(x => x.EmployeeID == 1) > 0;
Just keep in mind that Any is worst of those three because it fetches entity. Here is sql query generated for each:
exec sp_executesql N'select TOP (1) employee0_.EmployeeID as EmployeeID0_, employee0_.Name as Name0_ from Employee employee0_ where employee0_.EmployeeID=#p0',N'#p0 int',#p0=1
exec sp_executesql N'SELECT count(*) as y0_ FROM Employee this_ WHERE this_.EmployeeID = #p0',N'#p0 int',#p0=1
exec sp_executesql N'select cast(count(*) as INT) as col_0_0_ from Employee employee0_ where employee0_.EmployeeID=#p0',N'#p0 int',#p0=1
So I let myself to do some tests with your examples #Jamie Ide #Darius Kucinskas #Dmitry
So:
var exists = session
.CreateQuery("select 1 from Widget where _color = 'green'")
.SetMaxResults(1)
.UniqueResult<Int32?>()
.HasValue;
in my case was 18% faster than
bool exist = session.Query<Employee>()
.Any(x => x.EmployeeID == 1);
14% than
bool exist = session.Query<Employee>()
.Count(x => x.EmployeeID == 1) > 0;
and 8%
bool exist = session.QueryOver<Employee>()
.Where(x => x.EmployeeID == 1)
.RowCount() > 0;
So in my opinion even if hard coded query is fastest the
bool exist = session.QueryOver<Employee>()
.Where(x => x.EmployeeID == 1)
.RowCount() > 0;
is best option because of good habits and code clearness
Could always do a count.
I tend to use DetachedCriteria, so I'd have something like:
var criteria = // some criteria that will identify your object
var result = criteria
.GetExecutableCriteria(Session)
.SetProjection(Projections.RowCountInt64())
.UniqueResult();
return result > 0;
To expand on Darius Kucinskas' excellent answer, you can avoid fetching the entity using Select:
bool exist = session.Query<Employee>()
.Where(x => x.EmployeeID == 1)
.Select(x => x.EmployeeID)
.Any();
As mentioned, the query performance should be the same however I would expect this to reduce network traffic.
I think you are looking for this...
var fooExists = session.Query<Foo>().Any(f => /*condition*/);
var exists = 1 == session.CreateQuery("select 1 from MyEntity where Property = :value")
.SetValue("value", xxx)
.UniqueResult<Int32?>();
Based on Ricardo answer, this seems like the most efficient way to check if object exists using HQL. It doesn't COUNT and doesn't load the object unnecessarily:
var exists = session
.CreateQuery("select 1 from Widget where _color = 'green'")
.SetMaxResults(1)
.UniqueResult<Int32?>()
.HasValue;
It generates this SQL (note that this is SQLite, so LIMIT instead of TOP)
select
1 as col_0_0_
from
Widgets
where
Color='green' limit 1;
You can have a try:
public virtual T FindById<T>(int id)
{
return session.Get(typeof(T), id));
}
I created an extension method from the answers above. I choose to use the Any version but with a Select on the primary key the same amount of data will be returned depend on the primary key type.
public static bool Exists<TModel, TKey>(
this IQueryable<TModel> query, Expression<Func<TModel, TKey>> selector, TKey id)
where TKey : class
{
return query
.Select(selector)
.Any(x => x == id);
}
public static Task<bool> ExistsAsync<TModel, TKey>(
this IQueryable<TModel> query, Expression<Func<TModel, TKey>> selector, TKey id)
where TKey : class
{
return query
.Select(selector)
.AnyAsync(x => x == id);
}