How can I get linq pad to run my left join as show below?
var query =
from s in db.CDBLogsHeaders
.OrderByDescending(g => g.LogDateTime)
from sc in db.StyleColors
.Where(stylecolor => stylecolor.id == (int?)s.StyleColorID)
.DefaultIfEmpty()
from c in db.StyleHeaders
.Where(styleHeader => styleHeader.id == (int?)s.StyleHeaderID)
.DefaultIfEmpty()
select new
{
CDBLogsHeaderId = s.Id,
Merchandiser = c.Merchandiser,
Material = s.Material,
Season = s.Season,
LogsHeaderLogType = s.LogType,
PushFromTo = s.PushFromTo,
LinePlan = s.LinePlan,
QuikRefNumber = s.QuikRefNumber,
PLMOrigin = s.PLM_Origin,
SeasonOriginal = c.SeasonOriginal,
SeasonCurrent = c.SeasonCurrent,
StyleHeaderId = c.Id,
StyleCode = c.StyleCode,
StyleColorsColorCode = sc.ColorCode
};
query.Dump();
The sql that linq pad creates runs perfectly in Management Studio but linq-pad doesn't display any rows and gives this error
InvalidOperationException: The null value cannot be assigned to a
member with type System.Int32 which is a non-nullable value type.
How can I get linqpad to work so I can play with it?
In your anonymous type, make sure your ints are returning ints.
Change
StyleHeaderId = c.Id,
To
StyleHeaderId = (c.Id == null ? 0 : c.Id),
Related
I have a query in mySQL that produces desired output when entered into the mySQL terminal, however, I'm having trouble trying to write the same query in the Peewee ORM.
Here is the mySQL query:
select t.PATH, s.PATH from media_data as t
left outer join media_data as s on
s.SHOW = t.SHOW and s.EPISODE = t.EPISODE and s.SHOT = t.SHOT and s.FRAME = t.FRAME and t.LABEL_TYPE = 'target'
where s.LABEL_TYPE = 'source' and s.SHOW = 'doc_d' and s.EPISODE = '102'
union
select t.PATH, s.PATH from media_data as t
right outer join media_data as s on
s.SHOW = t.SHOW and s.EPISODE = t.EPISODE and s.SHOT = t.SHOT and s.FRAME = t.FRAME and t.LABEL_TYPE = 'target'
where s.LABEL_TYPE = 'source' and s.SHOW = 'doc_d' and s.EPISODE = '102';
And here is my attempt at the corresponding peewee query
s = media_data.alias()
t = media_data.alias()
predicate = (s.SHOW == t.SHOW and s.EPISODE == t.EPISODE and s.SHOT == t.SHOT
and s.FRAME == t.FRAME and t.LABEL_TYPE == 'target')
query = media_data.select(s.PATH, t.PATH).join(t, join_type=JOIN.FULL_OUTER, on=predicate).where(s.LABEL_TYPE == 'source' and s.SHOW == show and s.EPISODE == episode)
When I try to run python, it tells me there's a problem with 'JOIN.FULL_OUTER' even though it is used exactly as defined in the syntax.
There are a couple issues. First you need to use & instead of and in your predicates and to use parentheses to properly bind these:
predicate = ((S.show == T.show) &
(S.episode == T.episode) &
(S.shot == T.shot) &
(S.frame == T.frame) &
(T.label_type == 'target'))
Additionally, if your database is complaining about full outer join, perhaps it does not support this type of JOIN (and hence the reason for the awkward UNION query)?
If you have confirmed that your database does support full outer join, then the following should work:
T = MediaData.alias()
predicate = ((MediaData.show == T.show) &
(MediaData.episode == T.episode) &
(MediaData.shot == T.shot) &
(MediaData.frame == T.frame) &
(T.label_type == 'target'))
query = (MediaData
.select(MediaData.path, T.path)
.join(T, join_type=JOIN.FULL_OUTER, on=predicate)
.where(
(MediaData.label_type == 'source') &
(MediaData.show == 'doc_d') &
(MediaData.episode == '102')))
Query:
SELECT "t1"."path", "t2"."path"
FROM "mediadata" AS "t1"
FULL OUTER JOIN "mediadata" AS "t2" ON (
("t2"."show" = "t1"."show") AND
("t2"."episode" = "t1"."episode") AND
("t2"."shot" = "t1"."shot") AND
("t2"."frame" = "t1"."frame") AND
("t2"."label_type" = 'target'))
WHERE (
("t1"."label_type" = 'source') AND
("t1"."show" = 'doc_d')) AND
("t1"."episode" = '102'))
i have a linq query but in where clause is conditional. if eve.EventType is null then it will not include in where clause. How can we do with Linq lambda expression
var data= (from reg in product
join se in _order on reg.EventSessionId equals se.EventSessionId
join eve in Event on se.EventId equals eve.EventId
where eve.EventType == (EventType)eventType &&
((!string.IsNullOrEmpty(eve.EventName) && eve.EventName.Contains(SearchText, StringComparison.OrdinalIgnoreCase))
select (new OrderHistory
{
RegistrationId = reg.RegistrationId,
EventName = eve.EventName,
EventSesionName = se.EventSesionName,
})).ToList();
Thanks
This may help you.You should check null at first of your expression.
var data= (from reg in product
join se in _order on reg.EventSessionId equals se.EventSessionId
join eve in Event on se.EventId equals eve.EventId
where eve.EventType != null && eve.EventType == (EventType)eventType &&
((!string.IsNullOrEmpty(eve.EventName) && eve.EventName.Contains(SearchText, StringComparison.OrdinalIgnoreCase))
select (new OrderHistory
{
RegistrationId = reg.RegistrationId,
EventName = eve.EventName,
EventSesionName = se.EventSesionName,
})).ToList();
I am very new to writing LINQ statements, and I am struggling to write this simple SQL in LINQ form.
SELECT Type, COUNT(*) as [Total Submissions]
FROM Submission
GROUP BY Type
this is my attempt:
var query = from s in db.Submission
group s.Type
Type = s.Type
Total = s.Type.Count()
This is what my output should be:
Type Count of Type
Book 10
Chapter 15
Journal 8
Conference 4
Using LINQ syntax:
var result = from x in db.Submission
group x by x.Type into grp
select new {
Type = grp.Key,
Count = grp.Count()
};
Using lambda syntax:
var result = db.Submission
.GroupBy(x => x.Type)
.Select(x => new {
Type = x.Key,
Count = x.Count()
});
var loggedInHours = db.LoginLogs.Where(l => l.UserId == u.Id && l.UserSessionStop != null)
.Sum(ls=> ls.UserSessionStart.Subtract(ls.UserSessionStop.Value).Hours)
I am trying to calculate Total LoggedIn Hours using this linq query..
But its giving me this error
"Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."
I don't know whats wrong with it..plz help
Try if this works:
var loggedInHours = db.LoginLogs.Where(l => l.UserId == u.Id && l.UserSessionStop != null)
.Select(l=> new {
StartTime = l.UserSessionStart,
EndTime = l.UserSessionStop
})
.ToList()
.Sum(c=> c.StartTime - c.EndTime);
btw, Is UserSessionStop nullable? If yes, then what will be the value to be subtracted?
I have SQL database as follows
alt text http://img97.imageshack.us/img97/5774/dbimage.jpg
Now I want to filter the restaurant_detail table for the parameters:
1. cuisine 2. area
Can you help me to build LINQ query?
I presume you have a model generated either with LINQ to SQL or Entity Framework. Also, I'm assuming foreign key relationships have been set.
var details = db
.Cuisines
.Where(c => c.Cuisine=="something")
.SelectMany(c => c.RestaurantCuisines)
.Select(rc => rc.Restaurant.RestaurantDetails)
.Where(rd => rd.Area=="something")
;
Done with the linq query using following lines of code :
c = from q in dc.restaurant_cuisines
where q.cuisine.cuisine1.Contains(cuisine)
&& q.restaurant.price.ToString().Length == price.Length
select new NearBy { NearById = q.restaurant.id, NearByLongitude = (double)q.restaurant.longitude, NearByLatitude = (double)q.restaurant.latitude };
}
int[] ids = new int[c.Count()];
var lon = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.longtitude;
var lat = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.latitude;
foreach(NearBy n in c)
{
result = calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), n.NearByLatitude, n.NearByLongitude);
ids[i++] = n.NearById;
}
var r = from q in dc.restaurant_details
where 1 == 1 &&
(ids).Contains(q.restaurant_id)
select new Restaurant
{
Restora_id = q.restaurant_id.ToString(),
Name = q.restaurant.name,
Foodtype = q.restaurant.foodtype.foodtype1,
Avg_rating = q.restaurant.avg_rating.ToString(),
Featured = q.restaurant.featured.ToString(),
CuisineList = getCuisine(q.restaurant_id),
Restora_type = q.type,
Distance = Math.Round(calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), (double)q.restaurant.latitude, (double)q.restaurant.longitude), 2),
Newarrival = q.restaurant.newarrival.ToString(),
CountRecord = ids.Length.ToString()
};
var d = r.AsEnumerable().OrderBy(t => t.Distance);
var g = d.Take(recordSize + 10).Skip(recordSize);
return g.ToList();
Please note that above displayed code generated with some changes from the initial requirements.