Kindly convert my SQL to LINQ. I'm really desperate. It includes multiple filtering (2).
SELECT dbo.EmployeeAccess.EmpNo,
dbo.View_SystemAdminMembers.LNameByFName,
dbo.View_SystemAdminMembers.GroupName,
dbo.View_SystemAdminMembers.Role,
dbo.View_SystemAdminMembers.Active,
dbo.View_SystemAdminMembers.EmpNo AS Expr4,
dbo.View_SystemAdminMembers.RoleID
FROM dbo.EmployeeAccess
INNER JOIN dbo.View_SystemAdminMembers
ON dbo.EmployeeAccess.GroupID = dbo.View_SystemAdminMembers.GroupID
WHERE (dbo.EmployeeAccess.EmpNo = '50')
Thank you so much in advance.
Please try with the below code snippet.
var result =from e in context.EmployeeAccess
join v in context.View_SystemAdminMembers on e.GroupID equals v.GroupID
Where e.EmpNo == 50
select new { e.EmpNo,v.LNameByFName,v.GroupName,v.Role,v.Active,a.RoleID,v.EmpNo as VEmpNo };
Note : context is your DB Context object.
Let me know if any concern.
var results = (from ea in DbContext.EmployeeAccess
join sam in DbContext.View_SystemAdminMembers on ea.GroupId equals sam.GroupId
where ea.EmpNo = '50'
select new {
ea.EmpNo,
sam.LNameByFName,
sam.GroupName,
sam.Role,
sam.Active,
Expr4 = sam.EmpNo,
sam.RoleID
};
You didnt mention what your database context was, you'll have to fill that in yourself.
var res = (from x in ctx.EmployeeAccess
join y in ctx.View_SystemAdminMembers on x.GroupId equals y.groupId
where x.EmpNo = '50'
select new
{
x.EmpNo,
y.LNameByFName,
y.GroupName,
y.Role,
y.Active,
Expr4 = y.EmpNo,
y.RoleID
});
Note: do NOT use = when joining, but equals.
Related
I want to get rows with the count column and sum column like in the SQL command ... count(column1.table1) as countname, sum(column2.table1) as sumname ..., but I don't know the right way to write it in Linq, for the example:
var get = (from dbrg in db.data_barangs
join pbrg in db.pengiriman_barangs
on dbrg.kode_barang equals pbrg.kode_barang
join jdkp in db.jadwal_kapals
on pbrg.id_jadwal equals jdkp.id_jadwal
join dplb in db.data_pelabuhans
on jdkp.kode_pelabuhan equals dplb.kode_pelabuhan
join drdp in db.data_redpacks
on dbrg.kode_barang equals drdp.kode_barang
select new
{
KodeBarang = dbrg.kode_barang,
TanggalKedatangan = jdkp.tgl_kedatangan,
WaktuKedatangan = jdkp.waktu_kedatangan,
NamaPelabuhan = dplb.nama_pelabuhan,
Kota = dplb.kota,
Provinsi = dplb.provinsi,
NamaKapal = jdkp.kapal,
JumlahPacking = drdp.id_jadwal.Count(),
TotalBerat = drdp.total_berat_packing.Sum()
}).ToList();
Do you guys know the correct way?
The comments above correctly saying that group by should be used.
It is also good to know what keys should be used in the group by. In the select above you are listing a lot of properties and two of them should be grouped. Please take consider adding and removing some columns.
Why remove columns? Because of performance. If more columns used to group id_jadwal and total_berat_packing that has a cost at database level.
You may ask why add more columns? This can be because of correct functionality. Right now you have seven classic property, these are enough for correct summation? If not add more columns and create index for those
I did modify the query to fulfil grouping if you have question please let me know in the comment section.
var result = (from dbrg in db.data_barangs
join pbrg in db.pengiriman_barangs
on dbrg.kode_barang equals pbrg.kode_barang
join jdkp in db.jadwal_kapals
on pbrg.id_jadwal equals jdkp.id_jadwal
join dplb in db.data_pelabuhans
on jdkp.kode_pelabuhan equals dplb.kode_pelabuhan
join drdp in db.data_redpacks
on dbrg.kode_barang equals drdp.kode_barang
group new { JumlahPacking = drdp.id_jadwal, TotalBerat = drdp.total_berat_packing }
by new {
KodeBarang = dbrg.kode_barang,
TanggalKedatangan = jdkp.tgl_kedatangan,
WaktuKedatangan = jdkp.waktu_kedatangan,
NamaPelabuhan = dplb.nama_pelabuhan,
Kota = dplb.kota,
Provinsi = dplb.provinsi,
NamaKapal = jdkp.kapal,
}
into beratAndPackingSumGroup
select new
{
KodeBarang = beratAndPackingSumGroup.Key.KodeBarang,
TanggalKedatangan = beratAndPackingSumGroup.Key.TanggalKedatangan,
WaktuKedatangan = beratAndPackingSumGroup.Key.WaktuKedatangan,
NamaPelabuhan = beratAndPackingSumGroup.Key.NamaPelabuhan,
Kota = beratAndPackingSumGroup.Key.Kota,
Provinsi = beratAndPackingSumGroup.Key.Provinsi,
NamaKapal = beratAndPackingSumGroup.Key.NamaKapal,
JumlahPacking = beratAndPackingSumGroup.Select(x => x.JumlahPacking).Count(),
TotalBerat = beratAndPackingSumGroup.Sum(x => x.TotalBerat)
});
If JumlahPacking property is not correct you can call a distinction on it: beratAndPackingSumGroup.Select(x => x.JumlahPacking).Distinct().Count() this is require more performance.
I have a list as follows:
List<int> loc = new List<int>();
which I populate.
Note that the list stores int values.
I like to join this list to a db table as follow.
What I need to do is something like:
var result = (from pc in db.loc_details
join l in loc
on pc.locid = loc
select pc).ToList();
I get an error obviously: Cannot implicitly convert type 'System.Connection.Generics.List to 'int'.
What is the best approach to do this?
You're trying to join a single int to the entire list.
Try
var result = (from pc in db.loc_details
join l in loc
on pc.locid equals l
select pc).ToList();
although that will gve you a different error if you are using EF since it can't translate a join to an in-memory list to SQL. If that is the case, you can use Contains which gets translated to an IN clause:
var result = (from pc in db.loc_details
where loc.Contains(pc.locid)
select pc).ToList();
You wrote:
List<int> loc = new List<int>();
var result = (from pc in db.loc_details
join l in loc
on pc.locid = loc
select pc);
Answer yourself: what is the type of pc.LocId? And what is the type of loc?
Now look at your code:
on pc.locid = loc
by the way, shouldn't the = be equals or at least ==?
er have the following query in linq...
Whenever I try to run it I get a No comparison operator for type System.Int[] exception.
It's got something to do with the dictionary I am sure, but I don't understand why this isn't valid and was wondering if someone could explain?
// As requested... not sure it will help though.
var per = (
from p in OtherContext.tblPeriod
where activeContractList.Select(c => c.DomainSetExtensionCode).Contains(p.DomainSetExtensionCode)
select p).ToArray();
var com = (
from c in MyContext.tblService
join sce in MyContext.tblServiceExtension
on c.ServiceExtensionCode equals sce.ServiceExtensionCode
join sc in MyContext.tblServiceContract
on sce.ServiceContractCode equals sc.ContractCode
group sc by c.Period into comG
select new
{
PeriodNumber = comG.Key,
Group = comG,
}).ToArray();
var code =
(from c in com
join p in per on c.PeriodNumber equals p.PeriodNumber
select new
{
p.Code,
c.Group
}).ToArray();
var payDictionary = new Dictionary<int, int[]>();
// This is another linq query that returns an anonymous type with
// two properties, and int and an array.
code.ForEach(c => payDictionary.Add(c.Code, c.Group.Select(g => g.Code).ToArray()));
// MyContext is a LINQ to SQL DataContext
var stuff = (
from
p in MyContext.tblPaySomething
join cae in MyContext.tblSomethingElse
on p.PaymentCode equals cae.PaymentCode
join ca in MyContext.tblAnotherThing
on cae.SomeCode equals ca.SomeCode
where
// ca.ContractCode.Value in an int?, that should always have a value.
payDictionary[p.Code].Contains(ca.ContractCode.Value)
select new
{
p.Code,
p.ExtensionCode,
p.IsFlagged,
p.Narrative,
p.PayCode,
ca.BookCode,
cae.Status
}).ToList();
You won't be able to do this with a dictionary. The alternative is to join the three linq queries into one. You can do this with minimal impact to your code by not materializing the queries with ToArray. This will leave com and code as IQueryable<T> and allow for you compose other queries with them.
You will also need to use a group rather than constructing a dictionary. Something like this should work:
var per = (
from p in OtherContext.tblPeriod
where activeContractList.Select(c => c.DomainSetExtensionCode).Contains(p.DomainSetExtensionCode)
select p.PeriodNumber).ToArray(); // Leave this ToArray because it's materialized from OtherContext
var com =
from c in MyContext.tblService
join sce in MyContext.tblServiceExtension on c.ServiceExtensionCode equals sce.ServiceExtensionCode
join sc in MyContext.tblServiceContract on sce.ServiceContractCode equals sc.ContractCode
group sc by c.Period into comG
select new
{
PeriodNumber = comG.Key,
Group = comG,
}; // no ToArray
var code =
from c in com
where per.Contains(c.PeriodNumber) // have to change this line because per comes from OtherContext
select new
{
Code = c.PeriodNumber,
c.Group
}; // no ToArray
var results =
(from p in MyContext.tblPaySomething
join cae in MyContext.tblSomethingElse on p.PaymentCode equals cae.PaymentCode
join ca in MyContext.tblAnothThing on cae.SomeCode equals ca.SomeCode
join cg in MyContext.Codes.GroupBy(c => c.Code, c => c.Code) on cg.Key equals p.Code
where cg.Contains(ca.ContractCode.Value)
select new
{
p.ContractPeriodCode,
p.DomainSetExtensionCode,
p.IsFlagged,
p.Narrative,
p.PaymentCode,
ca.BookingCode,
cae.Status
})
.ToList();
Side Note: I also suggest using navigation properties where possible instead of joins. It makes it much easier to read and understand how objects are related and create complex queries.
Having a really hard time trying to figure out a "where in" equivalent in nHibernate.
I am using nHibernate 3. What's the best way to do something like this:
SELECT DISTINCT
U.ID as CID
FROM User U
WHERE
CID IN (
SELECT RID
FROM ResellerSites rs
INNER JOIN Locations l ON l.ID = rs.LID
WHERE l.ID = 14
)
I found an examples somewhere that says I need to have something like this:
var criteria = session.CreateCriteria(typeof(User));
var resellerSites = new[] { new ResellerSite { Id = 1 }, new ResellerSite { Id = 2 } };
criteria.Add(new InExpression("ResellerSite", resellerSites));
This is what I have so far:
var resellerSites = session.CreateCriteria<ResellerSite>("p")
.CreateCriteria("p.Locations", JoinType.InnerJoin)
.Add(Restrictions.Eq("locationID", locationId))
.List<ResellerSite>();
criteria.Add(new InExpression("ResellerSite", resellerSites));
var finalList = criteria.List<ResellerSite>();
The "criteria.Add(new InExpression" part is giving me an intellisense error, as InExpression seems to expect something like:
new[] { new ResellerSite { Id = 1 }, new ResellerSite { Id = 2 } };
Like in the first example.
Should I do a for loop like:
foreach (var site in resellerSites)
{
//somehow push into a new[] ?
}
or something like that or is there a better way?
Perhaps this entire approach is wrong?
I'd say that the typing problem comes from the double CreateCriteria and the single ToList()
Difficult to say without the table definitions, but, rereading you code, I wonder why you need the inner join with the locations.
May be you can rewrite your query as :
SELECT DISTINCT
U.ID as CID
FROM User U
INNER JOIN ResellerSites rs
on U.ID = rs.RID
and rs.LID=14
And have your code like (not tested and not optimal as you could have only one criteria query with join)
var resellerSites = session.CreateCriteria<ResellerSite>()
.Add(Expression.Eq("locationID", locationId))
.List<ResellerSite>();
criteria.Add(new InExpression("ResellerSite", resellerSites.ToArray()));
var finalList = criteria.List<ResellerSite>();
You can easily convert resellerSites to array using Linq:
criteria.Add(new InExpression("ResellerSite", resellerSites.ToArray()));
Also this question may help: Cannot use collections with InExpression
Is there somebody that could translate this query to Linq in C# . I was searching and I didn't find any query similiar to.
Thanks a lot guys!
SQL Sentence:
SELECT a.Amenaza, c.Nombre, c.Descripcion
FROM AmenazasEstablecer a, ControlesEstablecer c, Matriz_Amenazas_ControlesEstablecer m
WHERE a.IdAmenaza = m.IdAmenaza AND c.IdControl=m.IdControl;
You will have to have a DataContext created and specified, but once you do you could get away with:
MyDataContext context = new MyDataContext("SomeConnectionString");
var results = from a in context.AmenazasEstablecer
from c in context.ControlesEstablecer
from m in context.Matriz_Amenazas_ControlesEstablecer
where a.IdAmenaza == m.IdAmenaza && c.IdControl == m.IdControl
select new {
a.Amenaza,
c.Nombre,
c.Descripcion
});
var results = from a in context.AmenazasEstablecer
join m in context.Matriz_Amenazas_ControlesEstablecer
on a.IdAmenaza equals m.IdAmenaza
join c in context.ControlesEstablecer
on c.IdControl equals m.IdControl
select new {a.Amenaza, c.Nombre, c.Descripcion};