linq mysql : select multiple column and send the to view - mysql

I have selected multiple columns from my table, but I don't know how to pass it to my view.
var result = (from f in db.firmware
where f.firmware_release_type_text != ""
|| f.firmware_release_type_text != null
|| f.firmware_release_number_int != 0
select new{
f.firmware_release_type_text,
f.firmware_release_number_int
}).Distinct();
The result is f__anonymous2. I want to some how use it in my view. all the forums have just answered how to choose multiple columns, but nobody mentions how to pass them. I think I'm missing something obvious.
I want to be able to use this fields, or even merge them as one string.
I have tried Cast and so many other options which did not work.
When I try to force casting it sting, I get :
Unable to cast the type 'Anonymous type' to type 'System.String'
Thanks
UPDATE:
At the end I went with:
var result = (from f in db.firmware
where (f.firmware_release_type_text != "")
&& (f.firmware_release_type_text != null)
&& (f.firmware_release_number_int != 0)
select new{
f.firmware_release_type_text,
f.firmware_release_number_int
}
).Distinct();
List<string> result2 = new List<string>();
foreach (var item in result)
{
result2.Add(item.firmware_release_type_text
+ "-" + item.firmware_release_number_int);
}

If you want to return your data as a string you have to say how it should be formatted. You could for example change this:
select new
{
f.firmware_release_type_text , f.firmware_release_number_int
}
To this:
select f.firmware_release_type_text + " v" + (int)f.firmware_release_number_int

You have two options to create a model first, second format the data on the server side.

Related

How to filter based on multiple condition: ReactJS

Im playing around with React and json data, i have an input field to search data from the json file.
I can figure out how to search one key of the json data, is there any chance of some help.
My code is:
if(searchString.length > 0){
contactsData = contactsData.filter(function(l){
return l.name.toLowerCase().match( searchString );
});
}
where l.name i also want l.company and l.email.
One simple solution is concatenate all the three strings by using some character like *, # or any other, then check for searchString.
Like this:
if(searchString.length > 0){
let str;
contactsData = contactsData.filter(function(l){
str = `${l.name}# ${l.company}# ${l.email}`;
return str.toLowerCase().match( searchString );
});
}
Or you can individually check also, like this:
return (
l.name.toLowerCase().match( searchString ) ||
l.company.toLowerCase().match( searchString ) ||
l.email.toLowerCase().match( searchString )
);
search on multiple condition
in the given array you can search against firstName,lastName,email,phone.
if search query matched any of this values it will result of that.
{[{firstName:'Ali',lastName:'khan',email:'test#email.com',phone:12345}] .filter((a) =>
${a.firstName} ${a.lastName} ${a.email} ${a.phone}.includes(
your search filed value here
)
)

Strcpy Null Value Obtained From MySQL in C

I am using Connector C to connect to my MySQL database. A modification that I have made to the database recently now allows the data in my url field to be NULL. Connector C does not appear to have any problems reading the NULL value, but when I try and pass the value to my array structure using strcpy, the program crashes. Here is a simplified version of my code:
mysql_real_connect(conn, server,user,password,database, port, NULL, 0);
mysql_query(conn, "SELECT * FROM main WHERE propType IN ('Single Family', 'Condominium')");
res = mysql_use_result(conn);
while (((row = mysql_fetch_row(res)) != NULL) && (row[0] != NULL)) {
props[count].uniqueID = atol(row[0]);
strcpy(props[count].address, row[1]);
.
.
.
strcpy(props[count].url, row[55]);
count++;
}
By tracing out output of the rows, I have determined that it is this line of code that is failing, and it is ONLY failing when row[55] is (null):
strcpy(props[count].url, row[55]);
I am fairly new to C, and I assume that the problem lies in trying to use strcpy with a null string.
Any suggestions?
As is suggested above in the comment the problem is that row[55] has the value NULL and so strcpy() will crash. Maybe you want to try the following:
if (row[55] != NULL)
strcpy(props[count].url, row[55]);
else
props[count].url[0] = '\0';
Here is another example code which use a bit to store if the database contains NULL or a empty value:
if (row[55] != NULL)
{
strcpy(props[count].url, row[55]);
props[count].urlEmpty = false;
}
else
{
props[count].url = '\0'; // Maybe you can skip this
props[count].urlEmpty = true;
}
In this case you need to expand your structure.

Named query with optional parameter not working in mysql

I have a named query below for optional parameter which is flightNumber, departureAirport and arrivalAirport. But this query is not working when I don't give any value for these parameter.
#Query("from CapacityMonitor
where carrierCode = :carrierCode and
(:flightNumber IS NULL OR flightNumber = :flightNumber) and
(:departureAirport IS NULL OR departureAirport = :departureAirport) and
(:arrivalAirport IS NULL OR arrivalAirport = :arrivalAirport)
I can change a query but i have to use with #Query annotation only
So you want to keep your query the way it is and make it work with or without parameters. Well, you can't do that. If the query is expecting parameters, then you have to set them.
The best approach would be to leave the query the same way it is and set the parameters to NULL so that :param IS NULL returns TRUE in those cases and return all results. That way you will fake a match.
Anyway, the parameter has to be set always.
I would suggest using a Criteria Query to build a statement with custom WHERE clause.
Based on your example, it could look like this (depending on your data types):
public List<CapacityMonitor> getFlights(String carrierCode, String flightNumber, String departureAirport, String arrivalAirport) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<CapacityMonitor> query = builder.createQuery(CapacityMonitor.class);
Root<CapacityMonitor> root = query.from(CapacityMonitor.class);
query.select(root);
// Carrier code is mandatory
query.where(builder.equals(root.get("carrierCode"), carrierCode));
// Other properties are optional
if (null != flightNumber && flightNumber.length() > 0) {
query.where(builder.equals(root.get("flightNumber"), flightNumber));
}
// Use LIKE expression to match partially
if (null != departureAirport && departureAirport.length() > 0) {
query.where(builder.like(root.get("departureAirport"), "%" + departureAirport + "%"));
}
if (null != arrivalAirport && arrivalAirport.length() > 0) {
query.where(builder.like(root.get("arrivalAirport"), "%" + arrivalAirport + "%"));
}
return em.createQuery(query).getResultList();
}

Use of custom expression in LINQ leads to a query for each use

I have the following problem: In our database we record helpdesk tickets and we book hours under tickets. Between those is a visit report. So it is: ticket => visitreport => hours.
Hours have a certain 'kind' which is not determined by a type indicator in the hour record, but compiled by checking various properties of an hour. For example, an hour which has a customer but is not a service hour is always an invoice hour.
Last thing I want is that the definitions of those 'kinds' roam everywhere in the code. They must be at one place. Second, I want to be able to calculate totals of hours from various collections of hours. For example, a flattened collection of tickets with a certain date and a certain customer. Or all registrations which are marked as 'solution'.
I have decided to use a 'layered' database access approach. The same functions may provide data for screen representation but also for a report in .pdf . So the first step gathers all relevant data. That can be used for .pdf creation, but also for screen representation. In that case, it must be paged and ordered in a second step. That way I don't need separate queries which basically use the same data.
The amount of data may be large, like the creation of year totals. So the data from the first step should be queryable, not enumerable. To ensure I stay queryable even when I add the summation of hours in the results, I made the following function:
public static decimal TreeHours(this IEnumerable<Uren> h, FactHourType ht)
{
IQueryable<Uren> hours = h.AsQueryable();
ParameterExpression pe = Expression.Parameter(typeof(Uren), "Uren");
Expression left = Expression.Property(pe, typeof(Uren).GetProperty("IsOsab"));
Expression right = Expression.Constant(true, typeof(Boolean));
Expression isOsab = Expression.Equal(Expression.Convert(left, typeof(Boolean)), Expression.Convert(right, typeof(Boolean)));
left = Expression.Property(pe, typeof(Uren).GetProperty("IsKlant"));
right = Expression.Constant(true, typeof(Boolean));
Expression isCustomer = Expression.Equal(Expression.Convert(left, typeof(Boolean)), Expression.Convert(right, typeof(Boolean)));
Expression notOsab;
Expression notCustomer;
Expression final;
switch (ht)
{
case FactHourType.Invoice:
notOsab = Expression.Not(isOsab);
final = Expression.And(notOsab, isCustomer);
break;
case FactHourType.NotInvoice:
notOsab = Expression.Not(isOsab);
notCustomer = Expression.Not(isCustomer);
final = Expression.And(notOsab, notCustomer);
break;
case FactHourType.OSAB:
final = Expression.And(isOsab, isCustomer);
break;
case FactHourType.OsabInvoice:
final = Expression.Equal(isCustomer, Expression.Constant(true, typeof(Boolean)));
break;
case FactHourType.Total:
final = Expression.Constant(true, typeof(Boolean));
break;
default:
throw new Exception("");
}
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { hours.ElementType },
hours.Expression,
Expression.Lambda<Func<Uren, bool>>(final, new ParameterExpression[] { pe })
);
IQueryable<Uren> result = hours.Provider.CreateQuery<Uren>(whereCallExpression);
return result.Sum(u => u.Uren1);
}
The idea behind this function is that it should remain queryable so that I don't switch a shipload of data to enumerable.
I managed to stay queryable until the end. In step 1 I gather the raw data. In step 2 I order the data and subsequently I page it. In step 3 the data is converted to JSon and sent to the client. It totals hours by ticket.
The problem is: I get one query for the hours for each ticket. That's hundreds of queries! That's too much...
I tried the following approach:
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Ticket>(t => t.Bezoekrapport);
options.LoadWith<Bezoekrapport>(b => b.Urens);
dc.LoadOptions = options;
Bezoekrapport is simply Dutch for 'visitreport'. When I look at the query which retrieves the tickets, I see it joins the Bezoekrapport/visitreport but not the hours which are attached to it.
A second approach I have used is manually joining the hours in LINQ, but that does not work as well.
I must do something wrong. What is the best approach here?
The following code snippets are how I retrieve the data. Upon calling toList() on strHours in the last step, I get a hailstorm of queries. I've been trying for two days to work around it but it just doesn't work... Something must be wrong in my approach or in the function TreeHours.
Step 1:
IQueryable<RelationHoursTicketItem> HoursByTicket =
from Ticket t in allTickets
let RemarkSolved = t.TicketOpmerkings.SingleOrDefault(tr => tr.IsOplossing)
let hours = t.Bezoekrapport.Urens.
Where(h =>
(dateFrom == null || h.Datum >= dateFrom)
&& (dateTo == null || h.Datum <= dateTo)
&& h.Uren1 > 0)
select new RelationHoursTicketItem
{
Date = t.DatumCreatie,
DateSolved = RemarkSolved == null ? (DateTime?)null : RemarkSolved.Datum,
Ticket = t,
Relatie = t.Relatie,
HoursOsab = hours.TreeHours(FactHourType.OSAB),
HoursInvoice = hours.TreeHours(FactHourType.Invoice),
HoursNonInvoice = hours.TreeHours(FactHourType.NotInvoice),
HoursOsabInvoice = hours.TreeHours(FactHourType.OsabInvoice),
TicketNr = t.Id,
TicketName = t.Titel,
TicketCategorie = t.TicketCategorie,
TicketPriority = t.TicketPrioriteit,
TicketRemark = RemarkSolved
};
Step 2
sort = sort ?? "TicketNr";
IQueryable<RelationHoursTicketItem> hoursByTicket = GetRelationHours(relation, dateFrom, dateTo, withBranches);
IOrderedQueryable<RelationHoursTicketItem> orderedResults;
if (dir == "ASC")
{
orderedResults = hoursByTicket.OrderBy(sort);
}
else
{
orderedResults = hoursByTicket.OrderByDescending(sort);
}
IEnumerable<RelationHoursTicketItem> pagedResults = orderedResults.Skip(start ?? 0).Take(limit ?? 25);
records = hoursByTicket.Count();
return pagedResults;
Step 3:
IEnumerable<RelationHoursTicketItem> hours = _hourReportService.GetRelationReportHours(relation, dateFrom, dateTo, metFilialen, start, limit, dir, sort, out records);
var strHours = hours.Select(h => new
{
h.TicketNr,
h.TicketName,
RelationName = h.Relatie.Naam,
h.Date,
TicketPriority = h.TicketPriority.Naam,
h.DateSolved,
TicketCategorie = h.TicketCategorie == null ? "" : h.TicketCategorie.Naam,
TicketRemark = h.TicketRemark == null ? "" : h.TicketRemark.Opmerking,
h.HoursOsab,
h.HoursInvoice,
h.HoursNonInvoice,
h.HoursOsabInvoice
});
I don't think your TreeHours extension method can be converted to SQL by LINQ in one go. So are evaluated on execution of each constructor of the row, causing a 4 calls to the database in this case per row.
I would simplfy your LINQ query to return you the raw data from SQL, using a simple JOIN to get all tickets and there hours. I would then group and filter the Hours by type in memory. Otherwise, if you really need to perform your operations in SQL then look at the CompiledQuery.Compile method. This should be able to handle not making a query per row. I'm not sure you'd get the switch in there but you may be able to convert it using the ?: operator.

How do I use Count and Group in a select query in Linq?

I had the following Linq code:
var allRequests = model.GetAllRequests();
var unsatisifedRequests = (from request in allRequests
where request.Satisfied == false
select request)
.OrderBy(r => r.RequestedOn)
.GroupBy(r => r.RequestedCountryId);
After which I then did a foreach over unsatifiedRequests building a new TOARequestListSummary object for each. This meant if I "returned" 4 items from the query, it would make 4 calls to the DB, once per loop of the foreach to grab the individual rows.
This seems to be the wrong way to use Linq, so I tries to convert this query to one which used projections to return the TOARequestListSummary objects directly and I came up with:
var summaries = (from request in allRequests
where request.Satisfied == false
group request by request.RequestedCountryId into requestGroups
select new TOARequestListSummary
{
CountryName = requestGroups.First().RequestedCountry.Description,
RequestCount = requestGroups.Count(),
FirstRequested = requestGroups.First().RequestedOn
});
But when I run this, I get the following exception:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
I have got as far as knowing that the Linq equivalent to EXISTS is Contains, but I have no idea how to indroduce this into the query.
This should work for you:
var summaries = (from request in allRequests
where request.Satisfied == false
group request by request.RequestedCountry into g
select new TOARequestListSummary
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.Min(i => i.RequestedOn)
});
In your original version of this query (the second one you posted), your group's key was the RequestedCountryId. Though this will technically be grouping on that, you actually want to use the associated object. This way you'll have easy access to the needed properties and won't need to worry about grabbing the first item.
Sorry, this is an answer, rather than an additional comment to Ryan's answer, but it is too long to fit...
This gets very strange. In LinqPad the following works a treat:
from request in TOARequests
where request.Satisfied == false
&& request.Active == true
orderby request.RequestedOn
group request by request.RequestedCountry into g
select new
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.First().RequestedOn
}
But the following throws the same translation exception in C#
var summaries = (from request in context.Repository<TOARequest>()
where request.Satisfied == false
&& request.Active == true
orderby request.RequestedOn
group request by request.RequestedCountry into g
select new
{
CountryName = g.Key.Description,
RequestCount = g.Count(),
FirstRequested = g.First().RequestedOn
}).ToList();
The only difference I can see if the ToList(), but even without that when I try to enumerate the list, it throws the exception.