MVC Invalid length parameter passed to the LEFT or SUBSTRING function - c#

I have a SQL command wherein I am trying to join multiple columns in a single table which is,
dbo.tbl_Application AS APP on (APP.motor_no = SUBSTRING(R.remarks, CHARINDEX('|', R.remarks) + 1, LEN(R.remarks))) AND (Year(APP.date_created) = YEAR(R.txndate)) AND (APP.motor_no = M.motor_no)
Now I converted it to Linq
CONVERTED TO LINQ
join APP in db.tbl_Application on new
{ motor_no = R.remarks.Substring(5), R.txndate.Value.Year, motor_no2 = M.motor_no }
equals new
{ motor_no = APP.motor_no, APP.date_created.Value.Year, motor_no2 = APP.motor_no }
And then added to my existing linq which is:
EXISTING LINQ
from R in db.vwEtracs_Receipt
join RI in db.vwEtracs_ReceiptItem on new { parentid = R.objid } equals new { parentid = RI.parentid }
join IA in db.vwEtracs_IncomeAccount on new { objid = RI.acctid } equals new { objid = IA.objid }
join M in db.vwQVFS_Motor on new { motor_no = R.remarks.Substring(5) } equals new { motor_no = M.motor_no } into M_join
from M in M_join.DefaultIfEmpty()
join OOI in db.vwQVFS_OOI on new { operator_id = R.payerId } equals new { operator_id = OOI.operator_id } into OOI_join
from OOI in OOI_join.DefaultIfEmpty()
join CR in db.vwQVFS_COR on M.motor_id equals CR.motor_id into CR_join
from CR in CR_join.DefaultIfEmpty()
join F in db.vwQVFS_Franchise on new { or_id = R.objid } equals new { or_id = F.or_id } into F_join
from F in F_join.DefaultIfEmpty()
join T in db.vwQVFS_TODA on M.toda_id equals T.toda_id into T_join
from T in T_join.DefaultIfEmpty()
join RT in db.vwQVFS_RT on new { payer_id = R.payerId } equals new { payer_id = RT.payer_id } into RT_join
from RT in RT_join.DefaultIfEmpty()
join B in db.vwQVFS_Brand on M.brand_id equals B.brand_id into B_join
from B in B_join.DefaultIfEmpty()
If I include the line of code from above, I am getting the error Invalid length parameter passed to the LEFT or SUBSTRING function. but if I remove it, my Linq works perfectly.
What is making causing this error? Thanks in advance.

You getting the error because there is at least one record shorter than 5 characters in your database db.vwEtracs_Receipt.remarks column. So in your SQL, you don't pass length actually but in your linq you use Substring(int length). So the substring length can't be longer than the actual string length

Related

Linq Query to get latest of eact defect ID

In al_jira_defect_out table i have Batch_Insert_Timestamp, AL_Defect_ID columns along with other columns.And In this table there will be duplicate AL_Defect_IDs with different Batch_Insert_Timestamp.
As per below code in linq i am getting all records which are Jira_Status == 0
var defects = (from d in db.al_jira_defect_out
join p in db.al_jira_ref_defect_project on d.Defect_Product_ID.ToString() equals p.al_product_id
join t in db.al_jira_ref_defect_type on d.Defect_Type_ID equals t.type
where d.Jira_Status == 0
select new Issue
{
fields = new CreateIssue
{
project = new Project
{
key = g.jira_project_key
},
issuetype = new Issuetype()
{
name = t.jira_equivalent
},
description = d.Defect_ShortDesc,
summary = d.Defect_DetailDesc,
versions = new List<Versions>
{
new Versions {name = d.Defect_Release_DetectedIn}
},
priority = new Priority
{
name = d.Defect_Severity_Name
},
customfield_10182 = d.AL_Defect_ID.ToString(),
}
}).Select().ToList();
i am getting record with AL_Defect_IDs duplicate.
But i required latest records[Max(d.Batch_Insert_Timestamp)] of each d.AL_Defect_ID with all required columns
can any one please help me to get linq query
If you group on AL_Defect_IDs, you can order by Batch_Insert_Timestamp and take the last (latest) one:
var defects = (from d in db.al_jira_defect_out
join p in db.al_jira_ref_defect_project on d.Defect_Product_ID.ToString() equals p.al_product_id
join t in db.al_jira_ref_defect_type on d.Defect_Type_ID equals t.type
where d.Jira_Status == 0
group new { d, p, t } on d.AL_Defect_ID into dptg
let dpt = (from dpt in dptg order by dpt.d.Batch_Insert_Timestamp select dpt).Last()
select new // ... whatever using dpt
Your sample code doesn't use p in the select, so you could leave it out of the grouping.

Joining clause in linq

I've created three table's name: emps, emp_project, emp_location
now i want to select one column from each table, but when im executing join query so far getting this this error:
The type of one of the expressions in the join clause is incorrect.
Type inference failed in the call to 'GroupJoin'.
the query which im executing is:
from e in Emp_info
from p in Emp_projects
join l in Emp_locations
on new { e.User_id , p.Project_id } equals new { l.User_id, l.Project_id } into detail
from l in detail
select new
{
e.Middlename,
p.Project_name,
l.Location
};
query.Dump("Join query");
Don't know which of the clauses is causing the error!
My guess, is that the two anonymous types it is trying to compare aren't the same (also ensure that the properties are the same datatype).
Change
on new { e.User_id , p.Project_id } equals new { l.User_id, l.Project_id } into detail
To
on new { UserId = e.User_id, ProjectId = p.Project_id } equals
new { UserId = l.User_id, ProjectId = l.Project_id } into detail
this works for me
void Main()
{
var Emp_info = new List<Info>
{
new Info {Middlename = "Middlename",User_id = "1"}
};
var Emp_projects = new List<Project>
{
new Project{Project_id = "1",Project_name = "Project"}
};
var Emp_locations = new List<LocationInfo>
{
new LocationInfo{Location = "Location",Project_id="1",User_id = "1"}
};
/* your code */
var query = from e in Emp_info
from p in Emp_projects
join l in Emp_locations
on new { e.User_id , p.Project_id } equals new { l.User_id, l.Project_id } into detail
from l in detail
select new
{
e.Middlename,
p.Project_name,
l.Location
};
query.Dump("Join query");
/* your code */
}
class Info
{
public string User_id;
public string Middlename;
}
class Project
{
public string Project_id;
public string Project_name;
}
class LocationInfo
{
public string User_id;
public string Project_id;
public string Location;
}
So far i've come to this solution , by using more than one join at a time.
don't is it the right practice or not.
var query=
from e in Emp_info
join l in Emp_locations on e.User_id equals l.User_id // first join
join p in Emp_projects on l.Location_id equals p.Project_id // second join
select new
{
Name= e.Middlename,
Project = p.Project_name,
Location = l.Location
};
query.Dump();
finally got the answer.. this is working perfectly as i want
var query=
from e in db.emp_info
from p in db.emp_projects
join l in db.emp_locations
on new { username= e.User_id ,project_id=p.project_id } equals new { username=l.User_id,project_id= l.Project_id } into detail
from l in detail
select new
{
e,p,l
};
foreach (var q in query)
{
Console.WriteLine("{0} has done project like {1} in {2}",q.e.Middlename,q.p.project_name,q.l.location);
}
Console.ReadLine();
}
Console.ReadLine();

join condition is giving error in linq

i used below linq but it is giving error on first "join" keyword
(from st in queryResult.ToList()
join rf in rainfall.ToList() on Convert.ToInt32(st.StationID) equals Convert.ToInt32(rf.StationID)
join wl in water on
new { StationID = Convert.ToInt32(st.StationID), DataRecieved = rf.DataRecieved }
equals
new { StationID = Convert.ToInt32(wl.StationId), DataRecieved = wl.DataRecieved } into gj
from subpet in gj.DefaultEmpty()
select new
{
Stationname = st.Stationname,
Stationid = st.stationid,
State = st.state,
Datarecieved = rf.datarecieved,
dailyrainfall = rf.dailyrainfall,
cumlativerainfall = rf.cumrainfall,
waterlevel1 = subpet.waterlevel1
})
It is giving error "Does not contain a definition of "DefaultEmpty" and no extension method "DefaultEmpty" accepting a first argument.

The cast to value type 'System.Int32' failed because the materialized value is null.

I'm trying to return a list of results, however. Whenever there are no results, I receive the error message which I have posted above. However, it's strange because whenever I add the variable q instead of the return, it just returns no results instead and is fine with this. I would prefer to do it the way which I am currently doing it right now, does anybody know what is wrong with the query? Whenever I run it in LINQPad it works completely fine.
public IQueryable<ClaimNumberReport> GetClaimsByClaimNumber(int ClientID, int ClaimID) {
/*var q = */ return (from d in camOnlineDb.Details
join a in camOnlineDb.Areas
on new { a = d.ClientID, b = d.AreaID ?? 0 }
equals new { a = a.ClientID, b = a.AreaID }
where d.ClientID == ClientID
join r in camOnlineDb.Reasons
on new { a = d.ClientID, b = d.ReasonID ?? 0 }
equals new { a = r.ClientID, b = r.ReasonID }
join sd in camOnlineDb.SuppDepts
on new { a = d.ClientID, b = d.CategoryID ?? 0 }
equals new { a = sd.ClientID, b = sd.CategoryID } into sdd
from sd in sdd.DefaultIfEmpty()
join h in camOnlineDb.Headers
on new { d.ClientID, d.ClaimID}
equals new { h.ClientID, h.ClaimID }
where h.ClaimID == ClaimID
join su in camOnlineDb.Suppliers
on new { h.ClientID, h.SupplierID }
equals new {su.ClientID, su.SupplierID }
join cp in camOnlineDb.ClaimPacks
on new { h.ClientID, h.ClaimID }
equals new { cp.ClientID, cp.ClaimID }
join rev in camOnlineDb.Reviews
on new { h.ClientID, h.ReviewID }
equals new { rev.ClientID, rev.ReviewID }
join revp in camOnlineDb.ReviewPeriods
on new { a = rev.ClientID, b = rev.ReviewPeriodID ?? 0 }
equals new { a = revp.ClientID, b = revp.ReviewPeriodID }
join st in camOnlineDb.Statuses
on new { a = d.ClientID, b = d.StatusID ?? 0 }
equals new { a = st.ClientID, b = st.StatusID }
join stcm in camOnlineDb.StatusCategoryMappings
on new { st.ClientID, st.StatusID }
equals new { stcm.ClientID, stcm.StatusID }
join stc in camOnlineDb.StatusCategories
on new { stcm.StatusCategoryID }
equals new { stc.StatusCategoryID }
where stc.StatusCategoryTypeID == 1
select new ClaimNumberReport {
TypeID = d.ClaimTypeID,
CPAttached = cp.FileName,
ReviewPeriodName = revp.ReviewPeriodName,
ClaimID = d.ClaimID,
Line = d.ClaimLine,
AccountNo = su.AccountNo,
SupplierName = su.SupplierName,
Amount = d.Amount,
Status = st.StatusDesc,
DateSent = d.DateSent,
DayOS = d.DaysOS,
NominalPeriod = d.NominalPeriod,
SLInvoiceNo = d.SLInvoiceNo,
Area = a.AreaDesc,
DebitRef = d.DebitFile,
DebitDate = d.JournalDate,
DeductDate = d.DeductDate,
StatusCategoryID = stc.StatusCategoryID,
StatusCategoryDesc = stc.StatusCategoryDesc,
APLReason = r.ReasonDesc,
ClientID = d.ClientID,
DeptNo = sd.DepartmentID,
DeptName = sd.DepartmentName,
Agreed = d.Agreed
});
/*return q;*/
}
This error is caused by a situation where the query result type has a column/property of non-nullable type but the generated query results in a NULL value.
This could be considered a bug or not. It is hard to see what the L2S team should have done differently here. I think they should have added a better error message. This bug is insidious because it sometimes only strikes in production under unusual data...
Your left join (sd) seem not to match and one of the sd.* properties that you select must be an int. Solve that like this:
DeptNo = (int?)sd.DepartmentID, //Cast to nullable
d.CategoryID ?? 0
What are you doing here? This seems to be a way to make the join compile. It's better to use:
join r in camOnlineDb.Reasons
on new { a = d.ClientID, b = (int?)d.ReasonID }
equals new { a = r.ClientID, b = (int?)r.ReasonID }
This cast makes the anonymous type signatures compatible. The generated SQL should now be faster. If you say x ?? 0 that converts to COALESCE(x, 0) which can prevent index use and such.

Left join and case clause LINQ in Entity Framework

I am needing to make a left join and also use the select operator case.
My LINQ basic is this and works:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao
});
But I must add a new field and it should be formatted, then my LINQ looked like this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario.ToString("yyyy-MM-dd HH:mm:ss")
}
);
This error happens:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
If you add the ToList() or AsEnumerable() in db.AgendaHorario.ToList() and db.Agenda.ToList() and db.Profissional.ToList() error that appears is:
Object reference not set to an instance of an object.
What should I do to have a left join with case and fields and formatted fields
Try this:
resultado.Dados =
(
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = a.Horario
}).AsEnumerable().Select(x => new
{
id = x.id,
Medico = x.Medico,
start = x.start.ToString("yyyy-MM-dd HH:mm:ss")
}
);
try to set the string in a variable then assign it to your query like this:
var myValue = Horario.ToString("yyyy-MM-dd HH:mm:ss");
resultado.Dados = (
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
id = a.AgendaHorarioID,
Medico = e.Identificacao,
start = myValue
} );

Categories

Resources