System.Linq.Dynamic.Core GroupBy then Select - linq

I have a service that return IQueryable<T>.
I want to make this call with dynamic linq;
masterService.Grid().GroupBy(x=>x.Operation).Select(x=>new{Operation=x.Key});
I try below code;
masterService.Grid().GroupBy("Operation").Select("new(Operation.Key as Operation)");
But it throw error with message below;
No property or field 'Operation' exists in type 'IGrouping`2'
How can I do this?

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.

Error on GraphQL : no provided id but the store already contains an id of

I am very new to GraphQL and Apollo, and I don't understand what is wrong with the 'aliasEmail' field below. When I add this one to the query, I get this error message. When I remove it from the query, everything works perfectly.
It is well defined in 'types.graphql' and is just a simple string field.
index.js:2178 Unhandled (in react apollo:Apollo(withRouter(EmailSettingsContainer))) Error: Network
error: Error writing result to store for query:
query getCompanyForAliasEmailEditForm($companyId: ID) {
Company(id: $companyId) {
name
isTaxActive
telFixe
aliasEmail
telMobile
__typename
}
}
Store error: the application attempted to write an object with no
provided id but the store already contains an id of
Company:cje6xkcnxl83u01353a20p1t6 for this object. The selectionSet
that was trying to be written is:
Company(id: $companyId) {
name
isTaxActive
telFixe
aliasEmail
telMobile
__typename
}
It sounds like there's already another query being made elsewhere in the app that also returns the Company object and that query includes the id (or _id) field, while the query in this case does not. Apollo uses both the typename and id to generate the cache key for your query result (unless dataIdFromObject is used to modify this behavior), and so throws an error when it detects the above discrepancy. Try including the id field in your getCompanyForAliasEmailEditForm query.

Linq to entities custom function in select

In Linq to Entities one can't use standard c# method to modify the results in the "select" clause, canonical functions are required.
I need to invoke such query:
CoreEntities.Contracts.Select(
c=> new {
c.Name,
c.Type,
Role = MapToRole(c));
private string MapToRole(Contract contract) {
switch(contract.Type) {
case: CTypes.Main: return "somerole1";break;
case: CTypes.Secondary: return "somerole2";break;
// ...
default: break;
}
return "none";
}
The "MapToRole" is a C# method created just to declutter the linq query.
Is there a way to create a custom c# function that would be accepted by Entity Framework "linq to Entity" parser?
I've found a solution for query filters but not for data formatting.
It appears that as it's a simple transformation, there's no reason this needs to be translated by the provider. I would suggest simply adding AsEnumerable() before your Select() to "detach" your projection from the provider.
Alternatively you could have a CTypes property in your data type and a method/property that performs the transformation of that within your model.
As a side note, doing this particular transformation in your application layer means that you're only pulling through the enum value, not a string - therefore less data from the provider.

Retrieving selected fields from database using Hibernate

I'm retrieving a list of rows with selected fields from Oracle database using Hibernate. The retrieval is made by the following method in one of the DAOs in my application.
#SuppressWarnings("unchecked")
public List<Object[]> getOldFileName(String []ids)
{
int len=ids.length;
Long longType[]=new Long[len];
for(int i=0;i<len;i++)
{
longType[i]=Long.valueOf(ids[i]);
}
return sessionFactory.getCurrentSession().createQuery("select catId, catImage from Category where catId in(:id)").setParameterList("id", longType).list();
}
Here I'm fetching two fields categoryId and categoryImage as listed in the given HQL query based on the catId supplied as an array of String[] as a method parameter via Spring. It works fine and there is no question about it.
But regarding my requirements, retrieving catId again is completely unnecessary and I would like to remove catId from the list of fields in the query something simply like the following.
select catImage from Category where catId in(:id)
If I try to execute this query then the following call to the preceding method inside the Spring controller class,
String temp[]=request.getParameter("setDel").split(",");
List<Object[]> oldFileNames = categoryService.getOldFileName(temp);
//Invokes the preceding method in DAO.
causes the following exception to be thrown,
java.lang.ClassCastException: java.lang.String cannot be cast to
[Ljava.lang.Object;
The exception message indicates that java.lang.String cannot be cast to an array of Objects - Object[]. It appears that the HQL statement attempts to get only a single value of type String instead of retrieving List<Object[]>.
I just want to delete files which are stored in a directory after retrieving their names from the database and mentioning of catId in the list of fields in HQL is completely unnecessary.
Why do I need to add catId in the list of fields of the HQL statement in this scenario?
The return type for the list should be List. When only one column comes back hibernate does not put the result into and Object[]

Add values to object in LINQ to SQL expression

I have this contact list which I'm building using LINQ to SQL. The query to get a list of contacts is:
return db.Contacts.ToList();
In the list I also want to display each contact's primary e-mail address. To do this I first rewrite my query:
return (from db.Contacts
select c).ToList();
I found this nice way to do left joins:
return (from db.Contacts
from ce in ContactEmails.Where(x => x.ContactID == c.ContactID && c.IsPrimary).DefaultIfEmpty()
select c).ToList();
But now I want to add this PrimaryEmailAddress to my Contact object. To do this I have added a property (PrimaryEmailAddress) to the generated Contact class, using a partial class.
Is it possible in the LINQ query to add the value to c.PrimaryEmailAddress somehow? My solution right now is to create anonymous objects and then iterate them.
Here's one way to do it:
In your entity designer, create an association between your Contact class and your ContactEmail class (just guessing at your class names here). Here are some instructions on creating an association.
Then, configure your DataContext to load only your primary ContactEmail. Here are some instructions on filtering child data at the DataContext level.
And here is an entirely different way to do it:
In your partial Contact class, in your partial OnLoaded() method, query the primary ContactEmail. For example:
partial void OnLoaded()
{
// get your DataContext here
this.PrimaryContactEmail = db.ContactEmails
.Where(ce => ce.ContactID == this.ContactID && ce.IsPrimary)
.SingleOrDefault();
}

Resources