Passing DEFAULT value into new SqlParameter() - sql-server-2008-r2

How can i pass DEFAULT value into stored procedure in MVC4 .NET ?
I have this code
return Database.SqlQuery<Program>(
"spGetProgram #p1,#p2,#p3,#p4",
new SqlParameter("p1", (object)ID ?? "DEFAULT"),
new SqlParameter("p2", (object)displayStart ?? "DEFAULT"),
new SqlParameter("p3", (object)displayLength ?? "DEFAULT"),
new SqlParameter("p4", (object)searchString ?? "DEFAULT")
).ToList();
I tried
"DEFAULT" --> Error: Conversion Failed
null --> Error: parameter was not passed
DBNull.Value --> it pass N'' value but this Value is not DEFAULT
How can i do this ?

I found a workaround but it works only for one default parameter.
return Database.SqlQuery<int>(
"spGetProgramsCount " + (searchString != null ? "#p1" : ""),
(searchString != null ? new SqlParameter("p1", searchString) : null)
).First();
but when I have more parameters for example
return Database.SqlQuery<int>(
"spGetProgramsCount" + (searchString != null ? " #p1," : "")
+ (searchString2 != null ? " #p2," : "")
+ (searchString3 != null ? " #p3," : ""),
(searchString != null ? new SqlParameter("p1", searchString) : null), (searchString2 != null ? new SqlParameter("p2", searchString2) : null), (searchString3 != null ? new SqlParameter("p3", searchString3) : null)
).First();
I am getting
When executing a command, parameters must be exclusively database parameters or values.
and i believe it is because commas in the procedure, i don't know how to handle it :/

Related

Can't Get Count of More than one table fields Through Linq Query

My Aggregate Query
var attendanceAggregate = (from ed in _context.EmployeeDetail
join uf in _context.userInfo on ed.employeeCode equals uf.SSN
join ct in _context.EmployeeContract on ed.employeeCode equals ct.EmployeeCode
join chio in _context.checkinout on uf.USERID equals chio.USERID
join vlr in _context.LeaveRequest.Where(v => v.VerifiedByHR != null)
.Where(s => s.RequestDate >= FromDate && s.RequestDate <= ToDate)
on ct.ContractID equals vlr.ContractID into vlri
from vlr in vlri.DefaultIfEmpty()
join tlr in _context.LeaveRequest.Where(v => v.ApprovedBy != null && v.RequestedBy != null && v.RejectedBy == null)
.Where(s => s.RequestDate >= FromDate && s.RequestDate <= ToDate)
on ct.ContractID equals tlr.ContractID into tlri
from tlr in tlri.DefaultIfEmpty()
where uf.USERID == chio.USERID && chio.CHECKTIME != null
&& chio.CHECKTIME >= FromDate && chio.CHECKTIME <= ToDate
group new { ed, chio, ct, vlr, tlr } by new
{
ed.employeeCode,
ed.name,
ed.surName,
ed.nameDari,
ed.surNameDari
} into g
select new
{
g.Key.name,
//fullName = _culture.GetLanguageId() == 1 ? g.Key.name + ' ' + g.Key.surName : g.Key.nameDari + ' ' +
g.Key.surNameDari,
code = g.Key.employeeCode,
TotalPendingRequest=g.Count(s=> s.tlr.LeaveRequestID != null)
}).ToList();
and error that occured to me
'.Count(s => (Nullable)s.tlr.LeaveRequestID != null)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
This question needs details about EF Core version. EF Core 5 can translate this query but not earlier versions. But there is workaround using Sum
...
select new
{
g.Key.name,
g.Key.surNameDari,
code = g.Key.employeeCode,
TotalPendingRequest = g.Sum(s => s.tlr.LeaveRequestID != null ? 1 : 0)
}

'If null' operator to return an empty String

I am doing a null check with the operator '??'.
Text(contact.rating.toString() ?? " ",
However the text shows null when it is null, instead of
What's the best way to write this?
Because contact.rating is null, so you have to do the following
Text(contact.rating?.toString() ?? " "),
Here's one way:
Text(contact.rating != null ? contact.rating.toString() : " ")

Can't create a condition for null values in an array?

I am using linq expression trees to build a query.
My array:
string[] { null, null }
condition I want to implement:
x == null ? null : x.ToLower()
My linq expression looks like this:
{Param_0 => value(System.String[]).Any(Param_1 => (Param_0.FirstName.ToLower() == IIF((Param_1 == null), null, Param_1.ToLower())))}
This is my first attempt and I can't seem to find the correct way to do it
Constant = Expression.Condition(Expression.Equal(Constant, Expression.Constant(null, typeof(string))), Expression.Constant(null, typeof(string)), Expression.Call(Constant, "ToLower", null));
The expected result is to be able to call .ToLower() on elements that are not null
It seems to me that you want an expression that represents a function call with input a string, and output a string.
Expression<Func<string, string>>
How about a Lambda expression?
Expression<Func<string, string>> myExpression = (x) => (x==null) ? null : x.ToLower();
This expression can be used in a Queryable Select statement, like below:
IQueryable<string> myItems = new List<sring>()
{
"Abc",
null,
"DEF",
null,
"gHI",
}
.AsQueryable();
IQueryable<string> myLowerCaseItems = myItems.Select(myExpression);
foreach (string item in myLowerCaseItems)
{
if (item == null)
Console.WriteLine("<null>");
else
Console.WriteLine(item);
}
This yields the following output:
abc
def
ghi

EF Conditional Query to match with whatever information available doesn't work

I am trying to write a query to search employees by whatever of the 3 attributes are available in my object using Linq to Entity.
My object has First name, Last name, and Date of Birth.
My query looks like this (search is the object containing partial or full info)
var results = ctx
.emp
.Where(p =>
p.Fname == (search.Firstname ?? p.Fname)
&& p.Lname == (search.Lastname ?? p.Lname)
&& p.Dob == (search.Dob ?? p.Dob ))
The issue is that above query is matching employees with null values in each of those 3 columns along with the matching value. For instance if I provide search.Firstname to be John, it matches everyone with first name John AND everyone with null in first name.
How do I not match nulls in fields where a value is provided?
Haven't tested, but won't something like this work.
var results = ctx
.emp
.Where(p => (search.Firstname == null ? p.Fname == p.Fname : p.Fname == search.Firstname) ||
(search.Lastname == null ? p.Lname == p.Lname : p.Lname == search.Lastname) ||
(search.Dob == null ? p.Dob == p.Dob : p.Dob == search.Dob))
Please excuse the formatting. Using my mobile :)

Filter condition not working properly on list (C#3.0)

I have a datatable that has many NULL or " " strings. Next I am type casting the DataTable to a list .
Now if I want to filter those conditions on this list and get the resultant value(without NULL or String.Empty or " " records) what should I do?
My code
DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i =>
{
if (i[0] != null)
{
if ((i[0].ToString() != string.Empty)|| (i[0].ToString() != " "))
{
list = dt.AsEnumerable().ToList();
}
}
});
But I am getting all the records. It is not getting filtered.
Using C#3.0
Please help
Thanks
You're looking at i[0] so I'm going to assume that you're only interested in the first column of your table:
var rows = dt.AsEnumerable()
.Where(r => !r.IsNull(0) // check for DBNull
&& r[0] != null
&& r[0].ToString().Trim().Length > 0)
.ToList();
So that looks at every row but only returns the rows where the first column has a value and the string value is not empty or whitespace.