Can Dapper handle dynamic column header - dapper

I have a stored procedure that always returns a list of strings. However, based on the parameters passed to the stored procedure, the column heading for the list of strings will change. Is Dapper able to handle this? If so, how should it be handled?
conn.Open();
var p = new DynamicParameters();
p.Add("Search_Function_CD", searchFunction, DbType.String, ParameterDirection.Input);
p.Add("Search_Value", searchValue, DbType.String, direction: ParameterDirection.Input);
p.Add("o_resultset", dbType: DbType.Object, direction: ParameterDirection.Output);
var Results = (IDictionary<string, object>)conn.Query(sql: CommonConstants.ProcedureConstants.PKG_GET_SEARCH_RESULTS, param: p, commandType: CommandType.StoredProcedure);
foreach (object o in Results)
{
string element = Results.Values.ElementAt(1) as string;
searchResults.Add(element);
}
conn.Close();
return searchResults;

You can get the value by a dynamic column name or index:
var row = (IDictionary<string, object>)con.Query("select * from Products").First();
string name = row["ProductName"]; // column name 'ProductName'
// or:
string name = row.Values.ElementAt(1) as string; // column index 1

Related

Get Data from Two Tables Floor Flutter

I want to get data from two tables using floor in flutter, how can I do that?
this code for getting data from one table. this function inside database.g.dart:
Stream<List<Item>> getItems() {
return _queryAdapter.queryListStream(
'SELECT * FROM Item WHERE is_active = 1',
mapper: (Map<String, Object?> row) => Item(
id: row['id'] as int?,
item_id: row['item_id'] as String,
description: row['description'] as String,
salePrice: row['sale_price'] as double,
purchasePrice: row['purchase_price'] as double,
isActive: row['is_active'] as int),
queryableName: 'Item',
isView: false);
}
So the return will be Item objects but what if I have junction table from another tables and the command will be like this:
SELECT junctiont.*, item.*, client.*
FROM item
INNER JOIN junctiont
ON item.id = junctiont.item_id
INNER JOIN client
ON junctiont.client_id = client.id
How the function will be? and what will return?.
I found the answer by create new object to return the whole coming columns or you can return to list
#override
Stream<List<List>> getBillsMainInfo() {
return _queryAdapter.queryListStream(
'SELECT Bills.id, Biils.bill_number, Bills.total, Bills.datetime, Clients.name FROM Bills INNER JOIN Clients ON Bills.client_id = Clients.id WHERE Bills.is_active = 1',
mapper: (Map<String, Object?> row) => [
row['id'] as int,
row['bill_number'] as int,
row['datetime'] as String,
row['name'] as String,
row['total'] as double
],
queryableName: 'Bills',
isView: false);
}

Parameter names for Dapper multi-item Execute

With this code using Dapper .Execute:
using var c = new SqlConnection(ccstr);
var lst = new[] { 1, 2, 3 };
c.Execute("select #p", lst); // #p not recognized as parameter name
Is there a way to have a parameter name (here #p) for this native object list?
Leverage anonymous objects
using var c = new SqlConnection(ccstr);
var lst = new[] {
new {p = 1},
new {p = 2}
new {p = 3} };
c.Execute("select #p", lst);

Comparing two arrays of objects in Swift

I have two arrays of objects with different sizes.
First one with old data, second one with updated data from server (included old data with new), data can be mixed. I want to get difference between these arrays.
My class
class Station {
var dateOfIssue: Date
var region: String
var locality: String
var bsName: String
var freqIn: String
var freqOut: String
var networkType: String
var provider: String
var bsUsableName: String
...
}
Arrays I want to compare (example)
var a = [Station]()
var b = [Station]()
for _ in 0...5 {
a.append(Station(someRandomStationValue...)
}
b = a
for _ in 0...7{
b.append(Station(someRandomStationValue...) //array "b" will contain all that array "a" contains and some new values
}
How to compare these arrays comparing all fields between and get a new array with differences (like in java: b.removeAll(a))?
You can make use of Set which provides in-built .subtract() and .subtracting() methods which removes the common entries inside both the Sets
struct Station: Hashable,CustomStringConvertible {
var id: Int
var region: String
var locality: String
var bsName: String
// Just to provide a pretty print statement
var description: String {
return "ID: \(id) | region: \(region) | locality: \(locality) | bsName: \(bsName)"
}
}
var stations1 = Set<Station>()
var stations2 = Set<Station>()
for currentNumber in 0...3 {
stations1.insert(Station(id: currentNumber, region: "abc", locality: "abc", bsName: "abc"))
}
for currentNumber in 0...5 {
stations2.insert(Station(id: currentNumber, region: "abc", locality: "abc", bsName: "abc"))
}
// Caluculating the difference here
print(stations2.subtracting(stations1))
As pointed out by #koropok, a good solution is using Set. The first step is to conform your type to Hashable. For classes, you'd have to implement == and hash(into:) functions, but if you use struct you don't have to do anything else other than declaring the conformance. So:
struct Station: Hashable {
var dateOfIssue: Date
var region: String
...
}
Now you should be able to add Station into a Set. Thus:
var a = Set<Station>()
for _ in 0...5 {
a.insert(Station(...))
}
var b = Set<Station>()
a.forEach { b.insert($0) }
for _ in 0...7 {
b.insert(Station(...))
}
let c = b.subtracting(a)
Set also provides a handy initializer that you can use to turn your Station array into a set:
let s = Set(arrayLiteral: [your, station, objects])
As mentioned in comments by koropok you may use subtract method:
// Added to make original code functional
// Station must conform to Hashable protocol in order to be stored in the Set
struct Station: Hashable {
let id: Int
}
var a = [Station]()
for i in 0...5 {
a.append(Station(id:i))
}
var b = [Station]()
for i in 0...7{
//array "b" will contain all that array "a" contains and some new values
b.append(Station(id:i))
}
var c = Set(b)
// c will contain 6 and 7
c.subtract(a)

Mongoose search data by object

I want to make a search in database by JSON objects.
Here is my schema:
var patientSchema = new Schema({
firstname: String,
lastname: String,
age: String,
tel: String,
work: [workSchema],
});
My angular js request, sends an JSON object which will be:
{'firstname':'value', 'lastname':'value', 'age':'age','tel':tel}
Is there a way to search for the matches directly in the Patient Schema?
so if the JSON object contains only firstname value .. it will check that
in MySQL I would do,
SELECT * FROM patients WHERE firstname LIKE '%'.json.firstname AND .....
what I've tested is
var filter = "{'firstname': 'value', 'lastname': 'value', 'age':'value', 'tel': 'tel'}" //sent from angularjs client
var jsonFilter = JSON.parse(filter);
Patient.find().or([
{ 'firstname': { $regex: new RegExp(filter.firstname,'i') }},
{ 'lastname': { $regex: new RegExp(filter.lastname,'i') }},
{ 'age':{ $regex: new RegExp(filter.age,'i') }},
{ 'tel':{$regex: new RegExp(filter.tel,'i') }}]).exec(function(err, result) {
if ( err)
throw err;
res.json(result);
});
this works fine but ALL the data should be filled if the attributes are empty it will return undefined which will not get me the right data. since Angular JS sends only the $scope.data.
Is there a way to get all the data by my JSON object, and not rewriting all the JSON fields, because I need to make bigger filters in this project?
I do not know if it is the best way to do this, but it is a start. I would loop over your keys and build your query dynamically. By looping over your keys, you can add as many keys as you want. For each key, push your new regex to your query variable. Finally, use your result as query.
Here is the code:
var filter = {'firstname': 'value', 'lastname': 'value', 'age':'value', 'tel': 'tel'};
var query = {$or: []};
var keys = Object.keys(filter);
for(var i=0;i<keys.length;i++) {
var item = {};
item[keys[i]] = new RegExp(filter[key], 'i');
query.$or.push(item);
}
Patient.find(query).exec(function(err, result) {
if ( err)
throw err;
res.json(result);
});

LINQ : filter multiple string values - partial match - not full match as in multiple online examples

There are many good examples of searching multiple string values in LINQ e.g.
public static Product[] GetProducts(Guid[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Contains(p.ProductID)
select p).ToArray<Product>();
}
I have a list of Products that I need to match from a customer,
but I dont have an exact match - the Customers List Of Products contains my ProductID - but it is not exact - e.g.
Customer MyCompany
Description Description
Prod1XY Prod1
AProd2B Prod2
XXXProd3 Prod3
I thus cannot filter from the prodIDs [string array] because Prod1 does not contain Prod1XY
and thus cannot use the examples that are available.
How can I effectively change (reverse) the working examples
as to search CustomerProducts where it contains my Product Description please?
So to confirm : this is not a duplicate. The examples use the string[] x
input parameter and then searches:
where x.contains
I need help to get it : myProducts.Contains(x)
another online example modified to show the situation:
static void Main(string[] args) {
var table = new[] {
new { uid = 1 },
new { uid = 2 },
new { uid = 3 },
new { uid = 4 },
new { uid = 5 }
};
var stringarray = new[] { "1", "5", "10" };
var results = from xx in table
where table.Contains(stringarray)
select xx;
foreach (var result in results) {
Console.WriteLine("Result: " + result.uid.ToString());
}
}
It is not clear enough what you are trying to accomplish, but under assumption that you want to select all products where ProductID contains any value from specified list, it looks like that it:
public static Product[] GetProducts(string[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Any(id=>p.ProductID.Contains(id))
select p).ToArray<Product>();
}
Try this
public static Product[] GetProducts(string[] prodIDs)
{
return (
from p in GetProducts()
from q in prodIDs
where p.ProductID.IndexOf(q) > -1
select p)
.ToArray<Product>();
}

Resources