cosmos db LINQ query in documentation - linq

I am reading the cosmos db documentation here
https://3c5.com/DQRpv
There are several examples which say something like this
input.Select(family => family.parents[0].familyName);
where the input is IQueryable of object.
My question is how do I get an IQueryable of object but ?

You can try something like below:
Container container = await this.database.CreateContainerIfNotExistsAsync(containerId, "<partitionkeypath>");
var input = this.container.GetItemLinqQueryable<Family>();
input.Select(family => family.parents[0].familyName);
Where Family is the class defined to map with container properties.

Related

hotchocolate throws error when using UseFiltering() on a field

I have a pretty simple setyp where I'm putting graphql over an entityframework datacontext (sql server).
I'm trying to get filtering to work. I've tried adding .UseFiltering() to a field descriptor like so...
descriptor.Field(t => t.AccountName).Type<NonNullType<StringType>>().UseFiltering();
But it causes this error on startup...
HotChocolate.SchemaException: 'Unable to infer or resolve a schema
type from the type reference Input: System.Char.'
I assume I'm doing something wrong somewhere...
"UseFiltering" is supposed to be used to filter data which represents a collection of items in some way (IQueryable, IEnumerable, etc).
For instance, if you have users collection and each user has AccountName property you could filter that collection by AccountName:
[ExtendObjectType(Name = "Query")]
public class UserQuery
{
[UseFiltering]
public async Task<IEnumerable<User>> GetUsers([Service]usersRepo)
{
IQueryable<User> users = usersRepo.GetUsersQueryable();
}
}
In that example the HotChocolate implementation of filtering will generate a number of filters by user fields which you can use in the following way:
users(where: {AND: [{accountName_starts_with: "Tech"}, {accountName_not_ends_with: "Test"}]})
According to your example: the system thinks that AccountName is a collection, so tries to build filtering across the chars the AccountName consists of.

How to deal with readonly arguments from DataLoader - (GraphQL + Apollo in NextJS)

I have a loader function in order to fetch chefs from a database. So that loader receive an array of ids and what's is strange is that the ids have a readonly type.
When I try to pass that read-only type to the database query, it gives an error.
How can I fix the type definition?
Source code: https://github.com/LauraBeatris/graphql-with-nextjs/blob/master/pages/api/loader.ts
I fixed that according to #DanielRearden comment.
The function that the DataLoader instance receives uses generic types, so we're able to pass a type to the ids argument and then use it inside of the whereIn knex method.
new DataLoader((ids: string[]) => (
databaseClient
.table("chefs")
.whereIn("id", ids)
.select("*")
.then(rows => ids.map(id => rows.find(row => row.id === id)))
))

Entity being tracked despite AsNoTracking

I have an object, Client, with a navigation property that is a list of Order objects. Whenever I retrieve a Client object, I include the list of Orders, with AsNoTracking().
public new IQueryable<Client> FindByConditionNoTracking(Expression<Func<Client, bool>> expression)
{
return this.ClientContext.Set<Client>().Include(s => s.Orders)
.Where(expression).AsNoTracking();
}
In my UpdateClient repository method, I take in a Client object. I then attempt to retrieve that original client from the database (using Include to get the child Orders), map the Client param to the original, and save to the database. Over here, I do not use AsNoTracking, because I specifically want the changes to be tracked.
public new void Update(Client client)
{
var id = client.ClientId;
var original = this.ClientContext.Clients.Include(s => s.Orders).Where(s => s.ClientId == id)
.FirstOrDefault<Client>();
original = _mapper.Map(client, original);
this.ClientContext.Update(original);
}
The error I am getting is that an instance of Order with the same key value is already being tracked. A few problems with that:
Wherever the Client and the child Orders are retrieved for the purposes of display I use AsNoTracking.
The only place where I retrieve without AsNoTracking is where I get the original within this very method.
The bug isn't with the parent property. If I was improperly retrieving the Client elsewhere, wouldn't I have this error with the Client id itself? But the error seems to be only with the navigation property.
All insight is appreciated!
If anyone else runs into this: Automapper, when mapping collections, apparently recreates the entire collection. I solved the above issue by using Automapper.Collections in my mapping configuration. Thanks to Mat J for the tip!

Asp.Net Boilerplate...How to search in existing tables?

I want to apply queries on Boilerplate default tables in database. But boilerplate uses async methods. How to search in database by Boilerplate framework.
Could you elaborate your question?
I'm not sure what do you want to achieve.
If you uses IRepository you can use both synchronous and asynchronous methods by default.
If you're using asynchronous query and expecting immediate result you can use
If you have to wait for query results you can use Result property of Task. e.g.
var valueImWaitingFor = _repository.GetAllListAsync().Result;
Edit:
Assuming that you want to update user under login you can use provided UserManager class.
var user = loginResult.User; // get your user object
user.Name = "New name"; // edit property
// use one of 3 proposed solutions.
var updatedUser = _userManager.Update(user);
var updatedUser1 = _userManager.UpdateAsync(user).ConfigureAwait(false);
var updatedUser2 = AsyncHelper.RunSync(()=>_userManager.UpdateAsync(user));
Even if you don't use UserManager you can run async call similar way using second and third option.
If you want to use async methods as sync methods then there's a helper class in ABP.
var records = AsyncHelper.RunSync(() => _repository.GetAllListAsync());

AutoMapper Project().To() not working for interface destination

I have a situation in AutoMapper where I need to create a mapping with an interface destination. This is not a problem, and when using the normal Mapper.Map, it returns a proxy class as expected. However, when I try to do something similar with .Project().To(), which I need to use because an ORM is involved, I have issues. Here is the exact code that is failing which I replicated in a unit test:
AutoMapper.Mapper.CreateMap<RoleDto, IRole>(); //both just have Id/Name
IQueryable<RoleDto> roleDtos = new List<RoleDto>
{
new RoleDto { Id = 1, Name = "Role1" },
new RoleDto { Id = 2, Name = "Role2" }
}.AsQueryable();
//this works:
List<IRole> roles = roleDtos.Select(
roleDto => AutoMapper.Mapper.Map<IRole>(roleDto)
).ToList();
//this does not work:
List<IRole> roles2 = roleDtos.Project().To<IRole>().ToList();
I'm getting ArgumentException:
ArgumentException: Type 'UnitTestProject5.IRole' does not have a default constructor
In my real implementation the .Select is being performed on an Entity Framework collection, which is why I need to stick with .Project().To().
I have no issues with .Project().To() if the destination is not an interface. Additionally, I have no issues with the interface destination if I use .Map().
How can I get the interface destination and .Project.To() to work at the same time? Why is .Project.To() not giving me proxy classes like .Map() is? Any ideas?
Thanks!
Mapper.Map() takes the linq-to-objects route to materialize objects. As you said, AutoMapper is capable of creating types on the fly if the mapped target is an interface.
Project().To() is a way to translate the whole query, including the mapping, into SQL. Which is great, because only the properties that are required for the target object are included in the SQL query. However, the things AutoMapper does for creating types on the fly (undoubtedly some Refection voodoo) can never be part of an expression tree that can be converted into SQL. That's why Project.To simply tries to new up an object, even if it's an interface.
You'll have to use a concrete type as a mapping target. Of course, this type can implement an interface, so you can keep the independence you want.

Resources