Return Dictionary with Object Value in OrmLite - ormlite-servicestack

Is it possible in ServiceStack OrmLite to return a key-value dictionary with a value that's an object (class or anonymous type)?
For example:
var q = db.From<Customers>()
.Select(c => new { c.CustomerId, (c.FullName, c.Address) });
var list = db.Dictionary<int, object>(q);
In this case, I want the Dictionary item key to be CustomerId and value to be an object with two properties: FullName and Address.
I will be serialising the dictionary to JSON using Newtonsoft.Json for client-side lookup via key.

You can’t do a Tuple projection in an SqlExpression, you’d use it to select the columns you want:
var q = db.From<Customers>()
.Select(c => new { c.CustomerId, c.FullName, c.Address });
Then you can use C# 7 Tuple syntax to select custom columns, e.g:
var rows = db.Select<(int id, string name, string address)>(q);

Related

Get the last inserted item using Document Model or Object Persistence Model using .Net core with DynamoDB

I am able to get the last inserted item using low level API as showed in code below using .net core
But is it possible to get the last inserted item using high level API such as Document Model or Object Persistence Model?
Prefer Object Persistence Model if possible. I am not able to find a way to do it, also, I would like DynamoDB to query and return the last item only. I understand that I can get a list of items inserted and get the last item myself in memory, but it is not preferable since it require a lot more read and data transfer.
Thanks
public async Task<DailyStockRecordDao> GetTheLastInsertedItem(string tickerSymbol)
{
QueryRequest request = getTheLastItemRequest(tickerSymbol);
var response = await _dynamoDBClient.QueryAsync(request);
return null;
}
private static QueryRequest getTheLastItemRequest(string tickerSymbol)
{
string partitionName = ":v_PartitionKeyName";
var request = new QueryRequest
{
TableName = Constants.TableName,
KeyConditionExpression = $"{Constants.PartitionKeyName} = {partitionName}",
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
{ $"{partitionName}", new AttributeValue {
S = tickerSymbol
} }
},
// Optional parameter.
ConsistentRead = false,
Limit = 1,
ExclusiveStartKey = null,
ScanIndexForward = false
};
return request;
}
You can have the below data-structure to achieve this.
pk value
----------------------------------------------
key1 value1
key2 value2
key3 value3
latest {key: key1, value:value1}
While doing write, do 2 writes instead of 1. and while reading just do a get using pk=latest.
Can you add one more column called created_counter, and insert the value starting with numeric 1, then 2, then 3 and so on?
Make the created_counter as sort key.
To reverse the order, set the ScanIndexForward parameter to false.
Use limit 1, to get the last inserted data.

Retrieve id using multiple value From Firebase

I want to retrieve item id and get it to variable using items other value. according to this image ("get id where Brand="Manchee" and ItemName="Cream Cracker" and SubCategory="100g" ")
how write this function
Here you can try this solution.I think you wanted to query the database so you can fire query on your database based on your variable value.Just pass the key and value in this query and you can have all the data reside in the table which falls within this query.
var ref = firebase.database().ref("items");
ref.orderByChild("itemName").equalTo('Manchee').once("value", (items : any)=> {
console.log(items.key);
console.log(items.val());
let itemArray: any = [];
items.forEach((item) => {
itemArray.push({
key: item.key,
});
});
this.items = itemArray;
console.log("Prescription Data: ", itemArray);
});

AngularFire return last sorted record by custom key value

I have a collection of data in Firebase that uses my own custom keys to match what we are expecting from our API when it is completed. However, I need to get the highest value from a key that we created.
Data:
-Results
+20150514-1
+20150514-2
-20150521-1
Field1: data
Field2: data
...
+20150521-2
+20150528-1
+20150528-2
+20150528-3
+20150528-4
+20150604-1
+20150604-2
+20150604-3
In this case the key fields under my Results are dates with instances, then full records under each instance (Field1, Field2, ...). I am getting the data using
var FireBaseData = new Firebase(FIREBASE.URL);
var Results = FireBaseData.child('Results');
var LastResult = Results.orderByPriority().limitToLast(1);
var LastDate = LastResult.$id;
return LastDate.substr(0, 8);
However, I am now trying to get access to the $id, or even a data field in that last record, but I cannot get data.
I have also tried:
factory('Result' ...
var FireBaseData = new Firebase(FIREBASE.URL);
var Results = FireBaseData.child('Results');
var LastResult = Results.orderByPriority().limitToLast(1);
return $firebaseObject(LastDate);
and then try to access the Field on the returned item, without success.
var myDate = Result.Field2;

Joins and anonymous types in SQLite

I'm trying to do a few LINQ statements in SQLite but I'm getting a few problems.
First I'm trying to do a join. Here is my code:
var query = from client in db.Table<Client>()
join address in db.Table<AddressDetail>()
on client.AddressID equals address.AddressID
select new
{
ClientID = client.ClientID,
AddressID = address.AddressID,
Name = address.Name,
LastSaveDate = client.LastSaveDate
};
This fails and the error message I receive is : Joins are not supported.
Brilliant!!
So to get round this I split my code into 2 queries, so here is the updated code:
var query = db.Table<Client>();
foreach (var client in query)
{
var subQuery = from address in db.Table<AddressDetail>()
where address.AddressID == client.AddressID
select new
{
ClientID = client.ClientID,
AddressID = address.AddressID,
Name = address.Name,
LastSaveDate = client.LastSaveDate
};
foreach (var fullClient in subQuery)
{
//Do something here
}
}
This all seems to work until I try to loop round the results of the subQuery.
I receive the following error: No parameterless constructor defined for this object.
So do this mean that I can't use joins and anonymous types in SQLite?
Any ideas how I can get round this.
I'm using the SQLite, .Net 4.5 and am create a Windows 8 store app.
Had you try this?
just add ToList() to table you want to join.
var query = from client in db.Table<Client>()
join address in db.Table<AddressDetail>().ToList()
on client.AddressID equals address.AddressID
select new
{
ClientID = client.ClientID,
AddressID = address.AddressID,
Name = address.Name,
LastSaveDate = client.LastSaveDate
};

Correctly structuring this LinqToSql code

Normally I use stored procedures / work in SQL so apologies if I get the terminology slightly off here..
I have a database, with 3 seperate tables, and I need to search multiple fields in each of the 3 tables.
Im sure that I am not doing this the mose effective way, initially I am trying to do it in simple seteps to understand it.
I have the following;
var foo1 = entities.table1.Where(a => a.bodyText.Contains(searchString) || a.pageTitle.Contains(searchString));
var foo2 = entities.table2.Where(b => b.newsArticle.Contains(searchString) || b.newsArticle.Contains(searchString));
var foo3 = entities.table3.Where(c => c.ImageDescriptionContains(searchString));
I need to combine all these results into a single repeater for display.
At this point all 3 sets of data are in seperate, unique collections of anonymous data. So whats the best way of converting these into a single coherent bindable source?
I was thinking of itereating through each list in turn, pulling out the fields I need to display and putting them in a new class, then binding a lsit of these classes to the repeater.
But it all seems a bit clunky to me.
Is there a way of doing the search across all 3 tables in one go, and returning just the fields I need from each table, with a common name (i.e. in SQL I could write
select b.newsArticle as myText,
or
select newsArticle, ''
to return the news article and an empty string).
This would combine:
var foos = foo1.ToList();
foos.AddRange(foo2);
foos.AddRange(foo3);
To get just what you want:
var myExtractedValues = foos.Select(x => new {
Article = !string.IsNullOrEmpty(x.newsArticle))
? x.newsArticle
: string.Empty});
I have used an anonymous type here but you could swap the new {} with a type of your own.
I reverse the operator on the IsNullOrEmpty but that is just a personal preference (I prefer how is reads.)
To get all the results in one go you'll need to define a common class that will be used by all three queries to store the result. This class may be as well anonymous but I'll name it just for clarity.
class Data
{
public string Text{ get; set;}
}
Now, in your code you'll fetch instances of Data from database and you can use Union:
using( var entities = new YourDataContext)
{
var foo1 = entities.table1
.Where(a => a.bodyText.Contains(searchString) ||
a.pageTitle.Contains(searchString))
.Select(a => new Data{ Text = a.bodyText});
var foo2 = entities.table2
.Where(b => b.newsArticle.Contains(searchString) ||
b.newsArticle.Contains(searchString))
.Select(b => new Data{ Text = b.newsArticle});
var foo3 = entities.table3
.Where(c => c.ImageDescription.Contains(searchString))
.Select(c => new Data{ Text = c.ImageDescription});
return foo1.Union(foo2).Union(foo3);
}

Resources