I am writing a simple query in LINQ. In fact it is my first query in Linq. How the query is interpreted by compiler confused me. My query is not giving any result.
My Linq Query:
using (DataClasses1DataContext db = new DataClasses1DataContext(("connection string")))
{
var notif_sched_data = from sched in db.NOTIF_SCHEDs
join recip in db.NOTIF_RECIPs
on sched.NOTIF_RECIP_ID equals recip.NOTIF_RECIP_ID
select sched.NOTIF_RPT_ID;
}
which is interpreted by compiler as
SELECT [t0].[NOTIF_RPT_ID]
FROM [dbo].[NOTIF_SCHED] AS [t0]
INNER JOIN [dbo].[NOTIF_RECIP] AS [t1] ON [t0].[NOTIF_RECIP_ID] = [t1].[NOTIF_RECIP_ID]
and it gives no row as output. However,the SQL which is correctly working is :
select [NOTIF_SCHED].[NOTIF_RPT_ID]
from [NOTIF_SCHED]
INNER JOIN [NOTIF_RECIP] on [NOTIF_RECIP].[NOTIF_RECIP_ID]=[NOTIF_SCHED].[NOTIF_RECIP_ID].
Can somebody tell me what I need to change?
if i change the value around equals,it gives error as value is not in the right scope.
You are not materializing the query in anyway. the query will return you IQueryable of what you are selecting there. To get the query actually executed to the database you need to materialize the results with methods like .Count(), .FirstOrDefault(), .Tolist(), etc...
using (var db = new DataClasses1DataContext(("connection string")))
{
var query = (from sched in db.NOTIF_SCHEDs
join recip in db.NOTIF_RECIPs
on sched.NOTIF_RECIP_ID equals recip.NOTIF_RECIP_ID
select sched.NOTIF_RPT_ID);
var count = query.Count();
var list = query.ToList();
}
Thanks for your time. Actually query was correct. The problem was in the class file where we convert sql objects in OOPS objects.
i think the problem is for the last line.you should create a new anonymous type.so changing the last line to this may solve the problem :
select new { sched.NOTIF_RPT_ID };
also you can create a class like this one and set your values to an object of the class
public class data
{
public int id {get;set}
public somthing somthing {get;set}
...
}
now simply :
select new { id = sched.NOTIF_RPT_ID , something = x , ... };
Related
SELECT Meter.SerialNumber as serial,
SupplyPoint.Id as supplypoint,
SupplyType.Id as supplytype,
SupplyType.Name as supplytypename
FROM Meter
INNER JOIN SupplyPoint ON Meter.SupplyPointId = SupplyPoint.Id
INNER JOIN SupplyType ON SupplyPoint.SupplyTypeId = SupplyType.Id;
I have this query so that I might find the Supply Type of a meter based on it's serial. So far I've written this function:
var query = from meters in db.Meters
join supplyPoint in db.SupplyPoints on meters.SupplyPointId
equals supplyPoint.Id
join supplyType in db.SupplyTypes on supplyPoint.SupplyTypeId equals
supplyType.Id
select new { serial = meters.SerialNumber, type = supplyType.Name };
foreach (var meter in query)
{
if (meter.serial == serial)
return meter.type;
}
return "Meter Type Not Specified";`
So I call FindType(string serial) and it returns the type. Can anyone suggest better code for converting such a query? Any directions on where to learn more about LINQ are welcome too.
You are up for reading up quite a bit of material before you should get started.
Read about entity framework here.
Read about LINQ to SQL
here.
Hopefully, once you have you will realize that your problem boils down to the following code.
var result = context.YourTable.FirstOrDefault(r => r.Field == searchValue);
Without knowing much about what you are working with there's little that can be done to give you concrete help. First you want to get familiar with translating the sql statement to LINQ.
LINQ has a query syntax that starts with the from because that is how to define the datasource. SELECT FirstName FROM Authors becomes
from auth in db.Authors
select auth.FirstName
Where db is a reference to a datacontext as suggested in slugster's comment.
You can look for more information on linq at the following url
I'm trying to figure out how I can convert this same SQL query into a Linq query, but I'm not seeing a way to do NOT IN with Linq like you can with SQL.
SELECT COUNT(DISTINCT ID)
FROM References
WHERE ID NOT IN (
SELECT DISTINCT ID
FROM References
WHERE STATUS = 'COMPLETED')
AND STATUS = 'FAILED'
I need to know how many distinct [ID] values exist that contain a [Status] value of "FAILED" that do not also have a [Status] of "COMPLETED". Basically, if there is a failed without a completed, i need the distinct amount for that.
var query_5 = from r in Records where r.ID NOT IN(from r in Records where
r.Record_Status == "COMPLETED" ) && (r.Record_Status == "FAILED")
select r.ID;
var rec_5 = query_5;
Console.WriteLine(rec_5.Distinct());
This was my attempt to do it, but I'm receiving numerous errors as it is not the right way to code it. Any examples on how to accomplish this would be much appreciated!
This is how the rest of my setup is looking.
public class References
{
public string ID;
public string Record_Status;
}
public static List<References> Records = new List<References>
{
};
The rough equivalent of a (not) in is using Contains(). Since the inner subquery doesn't reference the outer, you could write it like this:
var completedIds =
(from r in ctx.References
where r.Status == "COMPLETED"
select r.Id).Distinct();
var count =
(from r in ctx.References
where !completedIds.Contains(r.ID)
where r.Status == "FAILED"
select r.Id).Distinct().Count();
You could use the Except method:
var completed =
(from r in References
where r.Record_Status == "COMPLETED"
select r.Id).Distinct();
var failed =
(from r in References
where r.Record_Status == "FAILED"
select r.Id).Distinct();
var countFailedNotCompleted = failed.Except(completed).Count();
Note that this does not require using Contains during iteration. The sequences will be compared all at once within the Except method. You could also tack ToArray() on to each of the distinct sequences to ensure minimal iteration in the case where you want to use those sequences more than once.
My question got down voted and put on hold because it is not specific enough. Ill try to specify
Before linq I would do this query
sql="SELECT products.* FROM products INNER JOIN productaccess ON products.id=productaccess.productid"
Now with the entity framework and link I can do this
var products = (from lProducts in db.Products
join lProductAccess in db.ProductAccess on lProducts.ID equals lProductAccess.ProductID
select lProducts).ToList();
But what if I want the flexibilty to get all products or only get the accessible objects
In sql I can do this
sql="SELECT products.* FROM products "
if (useProductAccess) {
sql+=" INNER JOIN productaccess ON products.id=productaccess.productid"
}
In Linq I have to make a separate linq statement.
if (useProductAccess) {
var productsFiltered = (from lProducts in db.Products
join lProductAccess in db.ProductAccess on lProducts.ID equals lProductAccess.ProductID
select lProducts).ToList();
} else {
var productsAll = (from lProducts in db.Products select lProducts).ToList();
}
Now, I could just get all the lProducts and then filter it in an additional linq statement with lProductAccess but then I am using an unnecessary large amount of data.
Is it an option to use:
var productsAccecible = (from lProductAccess in db.ProductAccess where lProductAccess.CustID==custID select lProductAccess).toArray();
var products = (from lProducts in db.Products
where (useProductAccess ?
productsAccessible.Contains(lProducts.ID)
: true)
select lProducts).ToList();
Linq provider will not know how to transform the ternary operator (? and :) in a valid sql, you could try this:
var query = db.Products;
if (useProductAccess)
query = query.Where(p => productsAccessible.Contains(p.ID));
var result = query.ToList();
I used the express profiler to see how the linq statement is translated into sql. It shows that the
productsAccessible.Contains(lProducts.ID)
part gets translated as
products.id in (comma seperated list of values)
My conclusion is it will work fine.
Are there possible drawbacks
Sure - it may produce an inefficient query, or it may not even work.
One thing to note is that your conditional operator won't compile; you can't return a bool and an int from the ternary operator.
Maybe you mean:
var products = (from lProducts in db.Products
where (useProductAccess ?
productsAccessible.Contains(lProducts.ID)
: true)
select lProducts).ToList();
or build your query up using method syntax and only add the where clause if necessary.
I want to convert the following SQL code into linq to sql but can't seem to find a way
select holder_name,agent_code,sum(total)
from agent_commission
group by agent_code
Can anyone help me? Am kinda stuck with this for quite a while.
Thanks in advance
UPDATE:
I tried the following
var query = (from p in context.Agent_Commissions
group p by new
{
p.agent_code
}
into s
select new
{
amount = s.Sum(q => q.total),
}
);
How do I select the other two columns? What am I missing?
In fact your SQL query works only when the corresponding relationship between holder_name and agent_code is 1-1, otherwise the Group by agent_code won't work. So your linq query should be like this:
var query = from p in context.Agent_Commissions
group p by p.agent_code into s
select new {
holder_name = s.FirstOrDefault().holder_name,
agent_code = s.Key,
amount = s.Sum(q => q.total)
};
Here is your linq query
from a in ctx.agent_code
group a by a.holder_name, a.code into totals
select { holder_name = a.holder_name,
code = a.code,
total = totals.Sum(t=>t.total)}
Given that you have linq2sql context in ctx variable and it has your table in it.
What is wrong with this code ?
I got this exception on the last line:
Unable to create a constant value of
type
'System.Collections.Generic.IEnumerable`1'.
Only primitive types ('such as Int32,
String, and Guid') are supported in
this context.
var query = from colT in dal.TBL_Gharardad
select colT;
if(lstTarafeGharardadIds.Count>0)
query = from q in query
join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id
select q;
dgvListeGharardad.DataSource = query.ToList();
The lastTarafeGharardadIds is a List<int>
I also test
dgvListeGharardad.DataSource = query;
Everything works well if if expression equals to false and this code
query = from q in query
join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id
select q;
doesn't run. But I can't understand I got the error on the last line (on this code):
dgvListeGharardad.DataSource = query.ToList();
I think linq can't join between an in-memory collection (lstTarafeGharardadIds) and a database table (dal.TBL_Gharardad, dal.v_Gharardad...).
Similar problem: Why won't this LINQ join statement work?
This should work:
var query = (from colT in dal.TBL_Gharardad select colT).AsEnumerable();;
if (lstTarafeGharardadIds.Count>0)
query = from q in query
join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id
select q;
dgvListeGharardad.DataSource = query.ToList();
Wow, thats hard to read!
Anyways, assuming your naming convention is right. you end up with: select colV. Selecting a column results in selecting a IEnumerable rather then a primitive value which your dataSource requires.
You can try and use SelectMany to select the actual value you need
dgvListeGharardad.DataSource = query.SelectMany(x => x.[YourProperty]).ToList();