select a.stakebuyinid , a.StakeBuyInValue from StakeBuyInByStakeCategories AS b
left join StakeBuyIns AS a on b.stakebuyinid = a.stakebuyinid
where b.GametypeId = 1 and b.StakeCategoryID = 3 and a.Currencyid = 1
above is my Simple SQL query i want to write in LINQ
I am using following LINQ query but Raise Error :- "The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."
var query = (from v in db.StakeBuyInByStakeCategories.Where(x => x.GameTypeId == gametypeid && x.StakeCategoryId == stakecategoryid)
join u in db.StakeBuyIns.Where(y => y.CurrencyId == currencyid)
on v.StakeBuyInId equals u.StakeBuyInId into Temp
from vus in Temp.DefaultIfEmpty()
select new {
vus.StakeBuyInId,
vus.StakeBuyInValue )
Assume
StakeBuyInByStakeCategoriesList as IEnumerable<StakeBuyInByStakeCategories>
and StakeBuyInsList as IEnumerable<StakeBuyIns>
(from b in StakeBuyInByStakeCategoriesList
from a in StakeBuyInsList
.Where(b.stakebuyinid equals a.stakebuyinid)
.DefaultIfEmpty()
.Where( b.GametypeId == 1 and b.StakeCategoryID == 3 and a.Currencyid == 1)
select new {Stakebuyinid=a.stakebuyinid, StakeBuyInValue=a.StakeBuyInValue}
The int in your model should be an int?, since nullable return values are possible.
Related
I have an SQL query which i am converting to Linq and i want to use Left Join instead of Inner Join.
I have tried DefaultIfEmpty() method but i haven't had any luck.
The Sql query:
SELECT t0.*, t1.* FROM entity AS t0
LEFT JOIN migration_logs AS t1 ON (CAST(t0.id AS CHAR) = t1.ObjectId and 'SASParty' = t1.ObjectType)
where t1.status is null || t1.Status <> '1' ORDER BY t0.id LIMIT 0, 10;
The Linq Query:
Entities
.Join(Migration_logs,
e => new { id = e.Id.ToString(), ObjectType = "SASParty" },
mlog => new { id = mlog.ObjectId, mlog.ObjectType },
(e, mlog) => new {e,mlog})
.Where(result => result.mlog.Status == null || result.mlog.Status != "1").DefaultIfEmpty().ToList()
I am using linqpad and when i execute the linq query it generates the following sql query:
SELECT t0.*
FROM entity AS t0
INNER JOIN migration_logs AS t1
ON ((CAST(t0.id AS CHAR) = t1.ObjectId) AND (#p0 = t1.ObjectType))
WHERE ((t1.Status IS NULL) OR (t1.Status <> #p1))
Some minor differences in the original query and generated sql query are there but i hope the problem statement is clear.
Any help would be appreciated.
I was able to find a solution with the linq to sql query and using into clause.
(from e in Entities
join mlog in Migration_logs
on new { id = e.Id.ToString(), ObjectType = "SASParty" }
equals new { id = mlog.ObjectId, mlog.ObjectType }
into results
from r in results.DefaultIfEmpty()
where r.Status == null || r.Status != "1"
select new
{
e
})
you want to perform the .DefaultIfEmpty() method on the quantity that you want to perform a left join onto. maybe this code snippet helps you
from e in Entities
join ml in Migration_lpgs on new { id=e.Id.ToString(), ObjectType="SASParty" } equals new { id=ml.Id.ToString(), mlog.ObjectType } into j
from e in j.DefaultIfEmpty()
where ml.Status == null || ml.Status != "1"
select e
This question already has answers here:
Error: Only primitive types or enumeration types are supported in this context EF
(2 answers)
Closed 5 years ago.
Trying to do this, different database:
var IDs = (from a in db1.Table1
join b in db1.Table2 on a.Id equals b.Id
orderby a.Status
where b.Id == 1 && a.Status == "new"
select new Company { a.Id }).ToList();
var query = (from c in db2.Company
join a in IDs on c.Id equals a.Id
select new Company { Id = a.Id, CompanyId = c.CompanyId }).OrderByDescending(z => z.CompanyId).ToList();
I got this:
Additional information: Unable to create a constant value of type 'M.Models.Company'. Only primitive types or enumeration types are supported in this context.
I think it is because of the ToList() at the second query.
The most likely issue here is that the 2nd query has no good way of representing that as a join. I suspect your best option would be to switch to Contains:
var IDs = (from a in db1.Table1
join b in db1.Table2 on a.Id equals b.Id
where b.Id == 1 && a.Status == "new"
select a.Id).Distinct().ToList();
var query = (from c in db2.Company
where IDs.Contains(c.Id)
select new { Id = a.Id, CompanyId = c.CompanyId }
).OrderByDescending(z => z.CompanyId).ToList();
This isn't ideal, and it will struggle for large lists, but it is at least a simpler pattern to represent into a parameterized query.
I am using LINQ query to get the rows with certain conditions. Here is the query.
var query = from v in dt1.AsEnumerable()
join c in dt2.AsEnumerable() on v.Field<int>("ID") equals c.Field<int>("ID")
where v.Field<string>("col1").Equals("abcd")
&& (c.Field<string>("col1").Equals("8776") || c.Field<string>("col1").Equals("8775"))
select new
{
ok = (from a in v where v.Field<string>("stah").Equals("1") select a).count(),
ok1 = (from a in v where v.Field<string>("stah").Equals("2") select a).count(),
ok2 = (from a in v where v.Field<string>("stah").Equals("3") select a).count()
};
The error is present in
ok = (from a in v where v.Field<string>("stah").Equals("1") select a).count()
The error is
could not find an implementation of the query pattern for source type
'system.data.DataRow'. 'Where' not found
Sample Input :
dt1
iD col1 stah
1 4567 1
2 8748 2
3 3487 3
4 8776 1
dt2
iD col1
1 4754
2 4576
Output
Get count of all rows where stah=1 && dt2.col1='4754'
But I cannot get it working. What is the correct syntax for this ?
If I have understood you correctly, then this is what you need:-
var query = dt1.AsEnumerable()
.Where(x => x.Field<int>("stah") == 1
&& dt2.AsEnumerable()
.Any(z => z.Field<int>("Id") == x.Field<int>("Id")
&& z.Field<string>("Col1") == "4754")
).Count();
#HarshitShrivastava mentioned that my previous attempt at the query didn't take into account all the where conditions.
How about this version using a mix of Linq query and Linq Lambda:
var query = from dataRows1 in dt1.AsEnumerable().Where(r => r.Field<string>("col1").Equals("abcd"))
join dataRows2 in dt2.AsEnumerable().Where(r => r.Field<string>("col1").Equals("8776") || r.Field<string>("col1").Equals("8775"))
on dataRows1.Field<int>("ID") equals dataRows2.Field<int>("ID") into b
select new
{
id = dataRows1.Field<int>("ID"),
ok = (from a in b where a.Field<string>("stah").Equals("1") select a).Count(),
ok1 = (from a in b where a.Field<string>("stah").Equals("2") select a).Count(),
ok2 = (from a in b where a.Field<string>("stah").Equals("3") select a).Count()
};
Note: I included the ID field in the projected output just for verifying the results. Remove as needed.
I want to learn why these two queries return different results.
This query returns 6:
var a = (from belg in contextArchive.Belgeler
join zrf in contextArchive.Zarflar on belg.Parent_ID equals zrf.ID
where belg.RefETTN == this.BelgeETTN
select new { zrf }).Count();
While this query returns 3:
var b = (from belg in contextArchive.Belgeler
join zrf in contextArchive.Zarflar on belg.Parent_ID equals zrf.ID
where belg.RefETTN == this.BelgeETTN
select new { zrf }).ToList();
countKabulRed = b.Count();
I believe there are some null values in b. The different between a and b is that a uses SQL's COUNT that neglects null values, while b's Count() includes both null and non-null values.
I have the following which works in SQL Query Analyzer.
select oh.*
from order_history oh
join orders o on o.order_id = oh.order_id
where oh.order_id = 20119 and oh.date_inserted = (
select max(date_inserted) from order_history where order_id = oh.order_id
group by order_id
)
How would I go about converting to LINQ? From test code, the compiler complained:
Error Operator '&&' cannot be applied to operands of type 'int' and 'System.DateTime'
My LINQ code:
var query = from ch in cdo.order_histories
join c in cdo.orders on ch.order_id equals c.order_id
where (ch.order_id.equals(1234)) &&
(ch.date_inserted == (cdo.order_histories.Max(p => p.date_inserted)))
select new OrderData() { };
Update: I was not using '==' for comparing.
Item remaining is this from my SQL query:
oh.date_inserted = (
select max(date_inserted) from order_history where order_id = oh.order_id
group by order_id)
How do I do this in LINQ?
It look like you are missing an equals sign somewhere when filtering on the order_id field. You probably have:
oh.order_id = 20119 && ...
Whereas you should have:
oh.order_id == 20119 && ...
Note the equality operator vs. the assignment operator. The result of an assignment operator is the value that was assigned, which is why your error says you can't compare operands of int and System.DateTime.
I also assume you have the same problem on the check against the value of date_inserted as well.
For the second part of your question, you are close in the conversion of the correlated sub query.
In SQL you have:
oh.date_inserted = (
select max(date_inserted) from order_history where order_id = oh.order_id
group by order_id)
And in LINQ-to-SQL you have
ch.date_inserted == (cdo.order_histories.Max(p => p.date_inserted))
You just have to add the filter for the order_histories which takes advantage of closures to capture the order_id value on the ch instance like so:
ch.date_inserted == (cdo.order_histories.
Where(ch2 => ch2.order_id == ch.order_id).
Max(p => p.date_inserted))
You could translate the SQL into LINQ... or you could write the LINQ for what you want.
var result = cdo.order_histories
.Where(oh => oh.order_id == 20119)
.OrderByDescending(oh => oh.date_inserted)
.Take(1)
.Select(oh => new {history = oh, order = oh.order}
.Single();
Agreed, some C# code is needed here, but off the top of my head- you're using "==" (evaluation) rather than "=" (assignment), correct? C# makes a distinction here where SQL does not.