Database.Count Null Value - sql

int userId;
int follow = 0;
if (Session["userId"] != null)
{
userId = int.Parse(Session["userId"].ToString());
follow = Model.Follow.Count(x => x.EdenUserId == userId);
}
Error Code: Value cannot be null.
There exists some users who don't follow anybody so Count should be 0 but it returns null.
If user is following any user, table is populated without problem.
Can anyone please explain how can I count when there is a possibility that the lambda expression might return null?

Try:
int userId;
int follow = 0;
if (Session["userId"] != null)
{
userId = int.Parse(Session["userId"].ToString());
follow = Model.Follow.Count(x => x.EdenUserId == userId) == null? 0: Model.Follow.Count(x => x.EdenUserId == userId);
}

Related

Best practice to check duplicate string data before insert data using Entity Framework Core in C#

I need an advice for my code. What I want to do is insert a row into a table using Entity Framework Core in ASP.NET Core.
Before inserting new data, I want to check if email and phone number is already used or not.
I want to return specifically, example if return = x, email used. If return = y, phone used.
Here's my code
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return 1;
}
return 2;
}
return 3;
}
I'm not sure with my code, is there any advice for the best practice in my case?
I just don't like these "magic numbers" that indicate the result of your checks.... how are you or how is anyone else going to know what 1 or 2 means, 6 months down the road from now??
I would suggest to either at least create a constants class that make it's more obvious what these numbers mean:
public class CheckConstants
{
public const int Successful = 1;
public const int PhoneExists = 2;
public const int EmailExists = 3;
}
and then use these constants in your code:
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
and also in any code that calls this method and need to know about the return status code.
Alternatively, you could also change this to an enum (instead of an int):
public enum CheckConstants
{
Successful, PhoneExists, EmailExists
}
and then just return this enum - instead of an int - from your method:
public CheckConstants Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
merge two database check to one Query
use SingleOrDefault instance of Single
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Select (e=>new {e.Email , e.Phone }).SingleOrDefault(e => e.Email == employee.Email || e.Phone == employee.Phone);
if (checkEmail == null)
{
context.Employees.Add(employee);
context.SaveChanges();
return 1;
}
else if (checkEmail.Email == employee.Email)
return 3;
else
return 2;
}

DBContext Query returns null

Codes inside Weekly returns a value. But in Monthly it returns null.
I tried to run the query in my SQL Server Management Studio and it returns the correct result. But in my code, it returns null.
I tried to breakpoint and the item.JobId is = 2.
Here is my codes.
if (item.Frequency == "Weekly")
{
if (item.StartDate.DayOfWeek.ToString() == DateTime.Now.DayOfWeek.ToString())
{
var jobname = _context.Jobs.Where(x => x.Id == item.JobId).FirstOrDefault();
if (ModelState.IsValid)
{
jobs.Id = 0;
jobs.Job = jobname.Job;
jobs.ClientName = jobname.ClientName;
jobs.ClientId = jobname.ClientId;
jobs.JobRate = jobname.JobRate;
jobs.Status = "Active";
}
}
}
else if (item.Frequency == "Monthly")
{
if (item.StartDate.Day.ToString() == DateTime.Now.Day.ToString())
{
var jobname = _context.Jobs.Where(x => x.Id == item.JobId).FirstOrDefault();
var a = jobname.Job;
if (ModelState.IsValid)
{
jobs.Id = 0;
jobs.Job = jobname.Job;
jobs.ClientName = jobname.ClientName;
jobs.ClientId = jobname.ClientId;
jobs.JobRate = jobname.JobRate;
jobs.Status = "Active";
}
}
}
And here is my SQL Query
SELECT TOP (200) Id, Job, ClientName, ClientId, JobRate, Status
FROM Jobs
WHERE (Id = 2)
It should return some value in it.
Both inner expressions of the ifs(ones controlling item.StartDate) are identical, so your problem lies in these controls. Can you make sure your code evaluates true for below condition?
if (item.StartDate.Day.ToString() == DateTime.Now.Day.ToString())

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

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...

Using " Is NULL/not NULL" in LINQ To SQL

i would like to translate this request in LINQ to SQL:
SELECT * from Agir where NouvelIncident='1' AND facturable is null
My try:
public static List<Agir> GetINDEFAgir()
{
DataClassesActilogDataContext db = ContextSingleton.GetDataContext();
List<Agir> list;
var v = from i in db.Agir
where i.facturable is null && i.NouvelIncident == true
select i;
list = v.ToList();
return list;
}
Looks like "is null" is not allowed in LINQ to SQL... i have a mistake.
Thanks in advance for your help
Use ==, 'is' is to check types
public static List<Agir> GetINDEFAgir()
{
DataClassesActilogDataContext db = ContextSingleton.GetDataContext();
List<Agir> list;
var v = from i in db.Agir
where i.facturable == null && i.NouvelIncident == true
select i;
list = v.ToList();
return list;
}
Doesn't this work?
var v = from i in db.Agir
where i.facturable == null && i.NouvelIncident == true
select i;
Linq-to-SQL should translate that to the proper SQL.

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);
}