Joining table does not accept null values. mvc5 c# - c#

i have a problem in joning table my 2 table is null '_departureItemsTableService' and '_departureTableService' and if the 2 table is null i got an error. what is the problem with my code. thanks
var list = (from t in tracking
join d in _departureItemsTableService.GetAll() on t.box_id.Trim() equals d.BoxNo.Trim() into mar from submark in mar.DefaultIfEmpty()
join dt in _departureTableService.GetAll() on submark.DepartureId equals dt.DepartureId into dep from depart in dep.DefaultIfEmpty()
select new TrackingListModel
{
Id = t.Id,
Name = t.firstname_s + " " + t.lastname_s,
Departure = depart?.DepartureDate ?? String.Empty,
});

Can you show how the .GetAll() is implemented? This will work fine if .GetAll() service returns an empty list instead of null.
Another possible workaround would be to assign the output in a variable outside of linq and initialize with an empty list like below -
var dItemTable = _departureItemsTableService.GetAll();
if (dItemTable == null)
dItemTable = new List<DepartureItems>();
Then use dItemTable in in the linq

Related

How do I change SQL Left Join to Lambda expression in C#?

I have three tables and one input value. As a first step, based on the #Input, I need to fetch DSType from DSTypes table. Now again I need to compare DSType of DSTypes with RTInput table's IType column value. If RTInput table has matching records then need to fetch the ID column value alone otherwise NULL should be assigned.
I achieved this logic in SQL but unable to achieve the same in Lambda expression.
I tried some code from google but that is not returning correct value.
DECLARE #ID
#ID = SELECT ID FROM DSMaster Where DSTId = #Input
SELECT RTI.ID FROM DSTypes(NOLOCK) DST
LEFT JOIN RTInput(NOLOCK) RTI
ON RTRIM(LTRIM(DST.DSType)) = RTRIM(LTRIM(RTI.IType))
WHERE DST.ID = #ID
Lambda expression which I tried:
using (BEContext beContext = new BEContext())
{
var mData = beContext.DSMaster.Where(r => r.DSTId = inputvalue);
var Id = beContext.RTInput.Join(beContext.DSTypes.Where(dst => dst.ID == mData.Id )).Select(z => z.ID).FirstOrDefault();
}
I think this may help.
using {BEContext beContext = new BEContext()){
var mData = (from p in beContext.DSMaster.Where(r=>r.DSTId == inputvalue)
join pr in beContext.RTInput on p.Id equals dst.ID
select new {
//select what you want
}).FirstOrDefault();

Using SQL instead of LINQ in Telerik Open Access

I'm using Telerik Open Access. I have two separate projects that have Open Access data and then a third project that has the bulk of my code. I've been working on a way to convert a simple (at least I thought it was) SQL query to LINQ so that I can get the data I need. I have not been successful. I've had to break a single LINQ query into separate queries, because of the need for the Trim() function (I think). This has led to a lengthy piece of code and I'm still not getting the same results as my SQL query.
So my question is, is there anyway to use SQL instead of LINQ to access the data in the Open Access projects? If so, can you show me the syntax to do that for my query?
If it is not possible to use SQL, can you show me show me the proper way to convert my SQL query into LINQ so that I get the same results?
Thank you.
My SQL query is
SELECT DISTINCT us2.ccustno, us2.dispname, us2.csiteno, so.s1_name
FROM [DALubeDeacom].[dbo].[dmbill] bi
INNER JOIN [DALubeDeacom].[dbo].[dmso1] so
ON bi.bi_s1id = so.s1_id
INNER JOIN [DALubeNew].[dbo].[usersecurity] us2
ON so.s1_name = us2.cparentno
WHERE
us2.ctype = 'JOBSITE'
AND us2.csiteno is not null
AND us2.csiteno != ''
AND bi.bi_smid = '22'
ORDER BY us2.csiteno
My LINQ query is
public List<DataModelSample> GetLocationsBySalesNo(string salesNo)
{
int iSalesNo = int.Parse(salesNo.Trim());
try
{
var dmso = (
from so in deacom.Dmso1
join qt in deacom.Dmbills
on so.S1_id equals qt.Bi_s1id
where qt.Bi_smid == iSalesNo
select new Dmso1
{
S1_id = so.S1_id
, S1_name = so.S1_name.Trim()
}
);
var usec = (
from us in dbContext.Usersecurities
where us.Cparentno != null && us.Cparentno.Trim() != "" && us.Ctype.Trim() == "JOBSITE" && us.Csiteno.Trim() != ""
select new Usersecurity
{
Ccustno = us.Ccustno.Trim(),
Csiteno = us.Csiteno.Trim(),
Dispname = us.Dispname.Trim(),
Cparentno = us.Cparentno.Trim()
}
);
var customers =
(
from us in usec
join so in dmso
on us.Cparentno equals so.S1_name
select us
);
customers = customers.GroupBy(x => x.Csiteno).Select(x => x.First());
List<DataModelSample> listLocations =
(
from c in customers
select new DataModelSample
{
customerID = c.Ccustno
,
origLocationName = c.Csiteno + " " + c.Dispname
,
origLocationID = c.Csiteno
}
).OrderBy(x => x.origLocationID).ToList();
return listLocations.ToList();
}
catch (Exception ex)
{
throw ex;
}
} // GetLocationsBySalesNo(userInfo.csalesno)
Edit 1 - 2-19-16
Tried a suggestion by ViktorZ. His query was similar to the one I first tried. It returned the error "Identifier 'Ctype' is not a parameter or variable or field of 'DALube_DeacomModel.Dmbill'. If 'Ctype' is a property please add the FieldAlias or Storage attribute to it or declare it as a field's alias." From an online search, it looked like this was do to "extended fields". I don't seemed to be using such fields. The only way I could get around this error was to break it into the smaller LINQ queries in my original question, which didn't produce the right results. Any suggestions?
Here's the code:
var query = (from bill in deacom.Dmbills
join so in deacom.Dmso1 on bill.Bi_s1id equals so.S1_id
join us in dbContext.Usersecurities on so.S1_name equals us.Cparentno
where us.Ctype == "JOBSITE"
&& us.Csiteno != null
&& us.Csiteno != string.Empty
&& bill.Bi_smid == iSalesNo
select new
{
ccustno = us.Ccustno.Trim(),
dispname = us.Dispname.Trim(),
csiteno = us.Csiteno.Trim(),
s1_name = so.S1_name.Trim()
}).Distinct();
One very crude approximation of your SQL query is:
var query = (from bill in deacom.Bills
join so in deacom.LubeDeacom on bill.bi_s1id equals so.s1_id
join us in deacom.UserSecurity on so.s1_name equals us.cparentno
where us.ctype = "JOBSITE"
&& us.csiteno != null
&& us.csiteno != string.Empty
&& bill.smid = '22'
order by us.csiteno
select new
{
us.ccustno.Trim(),
us.dispname.Trim(),
us.csiteno.Trim(),
so.s1_name.Trim()
}).Distinct();
// to check the translation result
string sql = query.ToString()
// to get the results
var result = query.ToList()
If this is not working for you, you can always fall back to Telerik Data Access ADO.NET API. Here is a documentation article how to use it.

unable to create a constant value of type anonymous type only primitive types

Using Entity Framework Version=6.0.0.0 to get to get common id and orderid as shown below.
var dt1 = from p in dt.AsEnumerable()
select new
{
Id = p.Field<int>("Id"),
OrderId = p.Field<int>("OrderId")
};
var dt2 = (from order in db.Orders
select new
{
order.Id,
order.OrderId
}).ToList();
var intersect = dt1.Intersect(dt2);
Based on the list of values in intersect. I need to select all the values from Orders Table.
Trying to used code getting error "unable to create a constant value of type anonymous type only primitive types"
var result= (from a in sync.Orders
where intersect.Any(b => a.Id == b.Id && a.OrderId == b.OrderId)
select a).ToList();
You are trying to "join" an EF query with an in-memory data set, which does not work because there's not a way to embed the list and the lookup in SQL. One option is to pull the entire table into memory with AsEnumerable:
var result= (from a in sync.Orders.AsEnumberable
where intersect.Any(b => a.Id == b.Id && a.OrderId == b.OrderId)
select a).ToList();
Another option is to concatenate the Id and OrderId into one value and use Contains since that can be translated to an IN clause in SQL:
var lookup = intersect.Select(i => i.Id + "-" + i.OrderId).ToList();
var result= (from a in sync.Orders
where lookup.Contains(a.Id + "-" + a.OrderId)
select a).ToList();

T-SQL to LINQ conversion

I have the following SQL statement
SELECT
c.CorpSystemID, c.SystemName ,
case when a.TaskItemID is NULL then 'false' else 'true' end as Assigned
FROM CorpSystems c
LEFT OUTER JOIN
(SELECT CorpSystemID, TASKItemID
FROM AffectedSystems
where TASKItemID = 1) a ON c.CorpSystemID = a.CorpSystemID
Can anyone please help me to convert this statement to LINQ?
Thank you.
Ok so assume you've got a list of your CorpSystem objects in a variable called Corpsystems and a list of your AffectedSystem objects in a variable called AffectedSystems. Try the following:
Edit: For a join on all Affected Systems, try this:
var matches = from c in CorpSystems
join a in AffectedSystems on c.CorpSystemId equals a.CorpSystemId into ac
from subSystem in ac.DefaultIfEmpty()
select new
{
c.CorpSystemId,
c.SystemName,
Assigned = subSystem != null && subSystem.TaskItemId != null
};
Or for just AffectedSystems that have a TaskItemId of 1:
var matches = from c in CorpSystems
join a in AffectedSystems.Where(as => as.TaskItemId == 1)
on c.CorpSystemId equals a.CorpSystemId into ac
from subSystem in ac.DefaultIfEmpty()
select new
{
c.CorpSystemId,
c.SystemName,
Assigned = subSystem != null && subSystem.TaskItemId != null
};
See the answers to the following SO question SQL to LINQ Tool, assuming that you do not want to go through the process by hand.

fill linq null data c# from previous line

I have bill details in list which contains the heading:
Account Numbers, Dates, Service Number, Charge category, Details, exgst, ingst, Detailsfill
Column :- Account Numbers, Dates, Service Number, Charge category, Details, exgst, ingst
are unique values but Column Detailsfill contains null. I want to allow my C# script to set values for Detailsfill where Detailsfill is null then insert data from previous row otherwise do nothing.
Note that Running total sets to 1 when detailsfill column has any text but continues to increment by 1 from 3 when detailsfill column is empty.
Below is the script I used.
var result_set2 = (from a in result_set1
join b in
(from x in result_set1a select x)
on
new {col1 = a.id, col2 = a.account, col3 = a.date, col4 = a.service, col5 = a.chargecat }
equals
new { col1 = b.id, col2 = b.account, col3 = b.date, col4 = b.service, col5 = b.chargecat } into outer
from tb in outer.DefaultIfEmpty()
where a.running_total1 != 0
where a.running_total1 != 2
where a.chargecat != ""
select new
{
running_total = a.running_total1,
account = a.account,
date = a.date,
service = a.service,
chargecat = a.chargecat,
details = a.details,
exgst = a.exgst,
ingst = a.ingst,
detailsfill = ((tb == null) ? "" : tb.details)
}).ToList();
foreach (var line in result_set2)
{
mobilenet_writerfile.WriteLine(line);
}
It sounds to me like you need a correlated subquery to populate detailsfill. This would be in the form of a select from a context with whatever parameters you determine fulfill your requirements. Example on second post of this thread: http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/18da37b0-b40e-444e-8ec7-7bd343e0c799/
Also you can find other examples here on stackoverflow: Is it possible to create a correlated subquery in LINQ?
More information would be required to write a contextual example but here is basically what it would look like:
Entities context = new Entities();
context.tbl.Where(t=>t.Id == someId)
.Select(t=> new() {
t.Id,
context.tbl2.First(tbl2=>tbl2.Id == t.Id).Value, //This is the subquery
t.whatever});
This is not a normal operation of Linq to hold onto a previous value and then use it later. That's not to say you can't make that work with Linq, but it would be more straightforward to keep that logic outside of the sequence operation. Simply iterate over the results after the query is composed.
var item = results.First();
foreach (var obj in results)
{
if (obj.detailsfill == null)
obj.detailsfill = item.detailsfill;
item = obj;
}
Note: If the first item happens to contain null in detailsfill, you will not pick up a value until the first item in the sequence that does contain a value. To get the first such item up front, simply use
var item = results.First(o => o.detailsfill != null);
// loop below

Categories