Fetching data filtered by system properties "CreatedAt" using Azure Mobile Services - azure-mobile-services

I am using Azure Mobile Services in my MVC project. I want to fetch records filtered by CreatedAt (which is an Azure table system property)
Following is the code I am using:
IMobileServiceTable<QuestionItem> bussinessQuestionItemTable =
CustomDeclaration.MobileService.GetTable<QuestionItem>();
queryToPass = "$filter=__createdAt ge datetime'2014-10-25T04:06:27Z'";
var coll = await bussinessQuestionItemTable.ReadAsync(queryToPass);
It always throws an exception The request could not be completed. (Bad Request) with StatusCode:400
I tried the same query with a DateTime field created by us and it worked fine, but it always fails with CreatedAt
Any help is appreciated.

In the .NET backend, the type of the CreatedAt column is DateTimeOffset, not DateTime. So to query based on that property you'll need to use the corresponding literal in your query:
IMobileServiceTable<QuestionItem> bussinessQuestionItemTable =
CustomDeclaration.MobileService.GetTable<QuestionItem>();
queryToPass = "$filter=__createdAt ge datetimeoffset'2014-10-25T04:06:27Z'";
var coll = await bussinessQuestionItemTable.ReadAsync(queryToPass);
Notice that if your type QuestionItem has a property tagged with [CreatedAt] (or [JsonProperty("__createdAt")] of type DateTimeOffset, then you can use a linq query as well:
IMobileServiceTable<QuestionItem> bussinessQuestionItemTable =
CustomDeclaration.MobileService.GetTable<QuestionItem>();
var coll = await bussinessQuestionItemTable
.Where(q => q.CreatedAt >= new DateTimeOffset(2014, 10, 25, 4:, 6, 27, TimeSpan.Zero))
.ToListAsync();

Related

how to get data from existing mongo collection using parse server?

I am new to Parse Server.
I am having an existing collection "users" in "employee" db in Mongodb.
I need to get the users data using Parse Server.
Below is the code:
var query = new Parse.Query(users);
query.find().then((data) => {
return data;
}).catch((error) => {
return error;
});
But I am getting the error "users" is not defined.
Need some valuable help.
if your Class really is called users (which is different to the built-in Parse Server Class called User), then use :
var query = new Parse.Query('users'); //note the quotation around 'users'
If you are in fact trying to query the built-in User class, use :
var query = new Parse.Query(Parse.User);
or
var query = new Parse.Query('_User');

EF6 can I update model/table after lambda querying?

I am lambda querying models (I make projection with other classes-GameBankVM, GameCouponBankVM) and at the end, I would like to loop throuh query result and update the model field. But I am getting The entity or complex type 'EPINMiddleWareAPI.Models.GameBankVM' cannot be constructed in a LINQ to Entities query.
Here is my sample code:
var gameBankResult = await (context.GameBanks.Where(g => g.productCode == initiate.productCode)
.Take(initiate.quantity)
.Select(g => new GameBankVM
{
quantity = g.quantity,
currency = g.currency,
initiationResultCode = g.initiationResultCode,
productCode = g.productCode,
productDescription = g.productDescription,
referenceId = g.referenceId,
responseDateTime = g.responseDateTime,
unitPrice = g.unitPrice,
totalPrice = g.totalPrice,
coupons = g.coupons.Select(c => new GameCouponBankVM
{
Pin = c.Pin,
Serial = c.Serial,
expiryDate = c.expiryDate
}).ToList()
})).ToListAsync();
if (gameBankResult.Count() != 0)
{
foreach (var item in gameBankResult)
{
item.referenceId = initiate.referenceId;
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
await context.SaveChangesAsync();
return Ok(gameBankResult);
}
How can I update referenceId on my GameBank model/table?
In this scenario, your data won't be updated because your query is returning a List of GameBankVM and not a List of GameBank, now technically speaking, you are breaking SRP, you should either update your data or query your data not both in the same method, you may want to refactor your method like this :
1.- Create a private method for data update, in this case, you query directly GameBank iterate thru list entries, make your changes and save them to the database, this same method can return List of GameBank to avoid another database roundtrip.
2.- In the controller after you call your new method, you can run the transformation query to convert List of GameBank to List of GameBankVM and return it to the view.
There are many other ways to do this, I'm just recommending this as a less impact way to make your controller work. But if you are willing to make things better, you can create a business layer where you resolve all your business rules, or you can use patterns like CQS or CQRS.

NHibernate error system.object[] when retrieving multiple entities in one query

I have a HQL query like this:
string QueryString = select client, transporter
from BaseClient as client, BaseTrans as transporter
where client.tr = transporter.Id and transporter.badge = 1
order by transporter.date;
But when I use this hql I receive the following error :
The value "System.Object[]" is not of type "xxx" and cannot be used in this generic collection.
Parameter name: value
Just like Example but, when I omit the Transporter entity in my select it works.
Like :
string QueryString = select client
from BaseClient as client, BaseTrans as transporter
where client.tr = transporter.Id and transporter.badge = 1
order by transporter.date;
But I need transporter in my select, because I use order by.
By the way, I have 2 hbm Client.hbm.xml and Transporter.hbm.xml. Each hbm have their own Class and Table.
i call it with :
IQuery requete = this.CreateQuery(QueryString);
IList<Client> executions = requete.List<Client>();
it hang on this line, when hibernate try to convert to the list
This happens because your result-set will likely be a multi-dimensional array where the first column represents a Client and the 2nd column contains a Transporter.
What happens if you change your code like this:
IQuery requete = this.CreateQuery(QueryString);
var result = requete.List();
var clients = result[0] as IEnumerable<Client>;
(I have no NHibernate installed on this system so I cannot just test something out quickly without creating and setting up a new project. :)

Not able to use IN query in LINQ with Entity Framework

I am using EF Framework to retrieve the data from SQL DB.
Sub Request Table looks like below:
In this table "org_assigneddept" is foreign key to another Department Table.
I have list of Departments as Input and I want to retrieve only those rows from DB whose org_assigneddept is matching the list.
Please find my whole code:-
private List<EventRequestDetailsViewModel> GetSummaryAssignedDeptEventRequests(List<EmpRoleDeptViewModel> vmDept)
{
List<EventRequestDetailsViewModel> vmEventRequestDeptSummary = new List<EventRequestDetailsViewModel>();
RequestBLL getRequestBLL = new RequestBLL();
Guid subRequestStatusId = getRequestBLL.GetRequestStatusId("Open");
using (var ctxGetEventRequestSumm = new STREAM_EMPLOYEEDBEntities())
{
vmEventRequestDeptSummary = (from ers in ctxGetEventRequestSumm.SubRequests
where vmDept.Any(dep=>dep.DeptId == ers.org_assigneddept)
select new EventRequestDetailsViewModel
{
SubRequestId = ers.org_subreqid
}).ToList();
}
}
It is giving the following error at the LINQ Query level:-
System.NotSupportedException: 'Unable to create a constant value of
type 'Application.Business.DLL.EmpRoleDeptViewModel'. Only primitive
types or enumeration types are supported in this context.'
Please let me know as how can I achieve the result
You cannot pass the department VMs to SQL, it doesn't know what those are.
// Extract the IDs from the view models.. Now a list of primitive types..
var departmentIds = vmDept.Select(x => x.DeptId).ToList();
then in your select statement...
..
where departmentIds.Contains(id=> id == ers.org_assigneddept)
..

how to select distinct with paging in entity framework?

how to select distinct with paging in entity framework?
i try to code below
var ll = _ctx.Cwzz_AccVouchMain.Select(v => v.Ddate).Distinct();
var l = ll.Skip(start).Take(limit).ToList();
but error:
must call orderBy method before skip
but my try
var ll = _ctx.Cwzz_AccVouchMain.Select(v => v.Ddate).Distinct();
var l = ll.OrderBy(v => v.Year).ThenBy(v => v.Month).ThenBy(v => v.Date).Skip(start).Take(limit).ToList();
error
ystem.NotSupportedException: LINQ to Entities not suppor type of "Date”。only support initial settlement,entity memeber,entity navagation property.
how to do?
Try this instead :
var ll = _ctx.Cwzz_AccVouchMain.Select(v => v.Ddate).Distinct();
var l = ll.OrderBy(v => v).Skip(start).Take(limit).ToList();
When you try to order by year, month and date, your query is not yet executed, and when .ToList() triggers it, it tries to build the appropriate sql query before sending it to your database server. However, your db has no clue about a Ddate.Year, Ddate.Month or Ddate.Date, because on the db side the Ddate field is a simple date, he doesn't understand your object with properties like the DateTime you use in C#.
If you wanted to order by month only (for example), you would have to trigger your query before that.