I'm Using the CRM SDK from PowerShell, Trying to query a contract linked to specific Account name, If I do the query against Account GUID I get the results, but I want to query against the name inside the EntityReference object, and not the GUID, for example (this works fine):
$query = new-object Microsoft.Xrm.Sdk.Query.QueryExpression('new_contract')
$query.Criteria.AddCondition('new_account', [Microsoft.Xrm.Sdk.Query.ConditionOperator]::Equal, $AccountGuid)
The Above results looks like that:
Key Value
--- -----
createdby Microsoft.Xrm.Sdk.EntityReference
createdon 21/10/2014
modifiedby Microsoft.Xrm.Sdk.EntityReference
modifiedon 28/02/2016
modifiedonbehalfby Microsoft.Xrm.Sdk.EntityReference
new_account Microsoft.Xrm.Sdk.EntityReference
[...] [...]
The new_account Properties are:
Id : dab2909d-6149-e411-93fc-005056af5481
LogicalName : account
Name : CustomerNameText
KeyAttributes : {}
RowVersion :
ExtensionData : System.Runtime.Serialization.ExtensionDataObject
I want to create a Query for new_contract with new_account Name LIKE CustomerNameText
I tried:
$query.Criteria.AddCondition('new_account',([Microsoft.Xrm.Sdk.EntityReference].Attributes['new_account']).Name, [Microsoft.Xrm.Sdk.Query.ConditionOperator]::Like, $AccountName)
But it not works get the following error:
Exception calling "RetrieveMultiple" with "1" argument(s): "Link entity with name or alias new_account is not found"
At line:2 char:5
+ $temp = $service.RetrieveMultiple($query);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FaultException`1
I hope i'm clear, but if not, comment with any question.
Powershell code is preferable, c# is ok as well
Thanks...
You cannot use QueryExpression criteria for EntityReference name. With EntityReference you can only use Guid.
If you want to Query by name, you can use LinkEntity in QueryExpression. You will have to use LinkCriteria
var q = new QueryExpression();
q.EntityName = "new_contract";
q.ColumnSet = new ColumnSet();
q.ColumnSet.Columns.Add("new_contractid");
q.LinkEntities.Add(new LinkEntity("new_contract", "account", "new_account", "accountid", JoinOperator.Inner));
q.LinkEntities[0].Columns.AddColumns("accountid", "name");
q.LinkEntities[0].EntityAlias = "temp";
q.LinkEntities[0].LinkCriteria.AddCondition("name", ConditionOperator.Equal, "yourAccountName");
P.SIf the above snippet, is not working for you. And you want to retrieve by accountName. On way to do this is use your existing code using Guid of account. But first you have to retrieve accountGuid by name. In that case
public Guid getAccountGuidByName(string name)
{
QueryExpression accountQuery = new QueryExpression("account");
accountQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "yourAccountName");
EntityCollection entCol = Service.RetrieveMultiple(accountQuery);
if (entCol.Entities.Count > 0)
{
return entCol.Entities[0].Id;
}
return Guid.Empty;
}
just for example i don't know how can you call function etc in powershell but i am providing c# code, as you said its ok if it in C# then use it like below :
$query = new-object Microsoft.Xrm.Sdk.Query.QueryExpression('new_contract')
$query.Criteria.AddCondition('new_account', [Microsoft.Xrm.Sdk.Query.ConditionOperator]::Equal, getAccountGuidByName("yourAccountName"));
Related
I have been trying to pass the columns I want to select in but out of the box it appears it is not possible. I have tried things like
#Query("SELECT :columns FROM USERS u WHERE u.LOCALE = :locale AND u.id IN (:ids)")
Flux<Users> retrieveExportData(#Param("columns") String columns,
#Param("locale") String locale,
#Param("ids") String[] ids);
and with
private final R2dbcEntityTemplate template;
I tried to create my own query and but that was not working because it has to be of type Criteria and that was just creating a complexity that just was not worth it.
It would be nice if I could add the columns like
criteriaList.add(
Criteria.where("LOCALE").is(locale)
);
Criteria criteria = Criteria.from(criteriaList);
and execute it like
Flux<Users> users = this.template.select(User.class)
.matching(Query.query(criteria))
.all();
or just calling the repository like in my first example.
Has anyone been able to do this successfully?
----- update 1 -----
I tried doing like so:
import org.springframework.r2dbc.core.DatabaseClient;
DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);
String sql = "SELECT " + columns + " FROM USERS u WHERE u.LOCALE=" + locale + " AND u.id IN (" + ids + ")";
return databaseClient.sql(sql)
.fetch()
.all().cast(User.class);
but Since Spring 4.3.6.RELEASE, LinkedCaseInsensitiveMap doesn't extend LinkedHashMap and HashMap, but only implements Map interface.
This results in a
Cannot cast org.springframework.util.LinkedCaseInsensitiveMap to User at java.base/java.lang.Class.cast
error.
I then tried the jooq approach suggested in the answers but it just produces syntax errors. Example
private final DSLContext ctx = DSL.using(connectionFactory);
private final Users users = ctx.newRecord(Users.USERS); <-- USERS not found
#Query("SELECT :columns FROM USERS u WHERE u.LOCALE = :locale AND u.id IN (:ids)")
public Flux<Users> retrieveExportData(
List<Field<?>> columns,
String locale,
String[] ids
) {
return Flux.from(ctx
.select(columns)
.from("USERS")
.where(users.LOCALE.eq(locale)) <--- LOCALE not found
.and(users.ID.in(ids)) <--- ID not found
).map(r -> r.into(Users.class)); <---- into not found
}
the library look promising. I will try to get it working.
You cannot replace a bind parameter (:columns) by syntactic elements like this, other than actual bind values. For this type of dynamic SQL, you'll have to resort to some sort of query building mechanism.
Perhaps look at jOOQ, which has R2DBC support? Your implementation would then look like this:
#Query("SELECT :columns FROM USERS u WHERE u.LOCALE = :locale AND u.id IN (:ids)")
public Flux<Users> retrieveExportData(
List<Field<?>> columns,
String locale,
String[] ids
) {
return Flux.from(ctx
.select(columns)
.from(USERS)
.where(USERS.LOCALE.eq(locale))
.and(USERS.ID.in(ids))
).map(r -> r.into(Users.class));
}
Disclaimer: I work for the company behind jOOQ.
you can write dynamic SQL like so.
import org.springframework.r2dbc.core.DatabaseClient;
DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);
String sql = "SELECT " + columns + " FROM USERS u WHERE u.LOCALE=" + locale + " AND u.id IN (" + ids + ")";
return databaseClient.sql(sql)
.fetch()
.all().cast(User.class);
and you will need this dependency
implementation "org.springframework.boot:spring-boot-starter-data-r2dbc:2.6.2"
i am new in web services, am using spring-boot for creating web services, whereas, while giving the request with http://localhost:8085/user/30?name=abc, I am getting null for the id property.`
#GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String getUser(#PathParam("id") Long id,
#QueryParam("name") String name){
System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}
edited to add screenshot.
screenshot taken from Postman
Thanks in advance.
You need to use #PathVariable because you are using spring-rest not #PathParam that is a JAX-RS annotation
#GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String getUser(#PathVariable("id") Long id,
#QueryParam("name") String name){
System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}
I noticed you are mixing Jax-RS annotation with Spring annotation
Try this and it will fix your problem
#GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String getUser(#PathVariable("id") Long id,
#RequestParam("name") String name){
System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}
For the id variable you must use #PathVariable annotation and for the name parameter use #RequestParam.
Here is a full working solution:
#RestController
#RequestMapping("/user")
public class UserController {
#GetMapping("/{id}")
public String getUser(#PathVariable Long id, #RequestParam String name) {
System.out.println(" Got id by path param : " + id + " And Got name using Query Param " + name);
return " Got id by path param : " + id + " And Got name using Query Param " + name;
}
}
See here for more details.
Now when you make a request
$ curl http://localhost:8085/user/30?name=abc
you get a response:
Got id by path param : 30 And Got name using Query Param abc
I have some word templates(maybe thousands). Each template has merge fields which will be filled from database. I don`t like writing separate code for every template and then build the application and deploy it whenever a template is changed or a field on the template is added!
Instead, I'm trying to define all merge fields in a separate xml file and for each field I want to write the "query" which will be called when needed. EX:
mergefield1 will call query "Case.Parties.FirstOrDefault.NameEn"
mergefield2 will call query "Case.CaseNumber"
mergefield3 will call query "Case.Documents.FirstOrDefault.DocumentContent.DocumentType"
Etc,
So, for a particular template I scan its merge fields, and for each merge field I take it`s "query definition" and make that request to database using EntityFramework and LINQ. Ex. it works for these queries: "TimeSlots.FirstOrDefault.StartDateTime" or
"Case.CaseNumber"
This will be an engine which will generate word documents and fill it with merge fields from xml. In addition, it will work for any new template or new merge field.
Now, I have worked a version using reflection.
public string GetColumnValueByObjectByName(Expression<Func<TEntity, bool>> filter = null, string objectName = "", string dllName = "", string objectID = "", string propertyName = "")
{
string objectDllName = objectName + ", " + dllName;
Type type = Type.GetType(objectDllName);
Guid oID = new Guid(objectID);
dynamic Entity = context.Set(type).Find(oID); // get Object by Type and ObjectID
string value = ""; //the value which will be filled with data from database
IEnumerable<string> linqMethods = typeof(System.Linq.Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Select(s => s.Name).ToList(); //get all linq methods and save them as list of strings
if (propertyName.Contains('.'))
{
string[] properies = propertyName.Split('.');
dynamic object1 = Entity;
IEnumerable<dynamic> Child = new List<dynamic>();
for (int i = 0; i < properies.Length; i++)
{
if (i < properies.Length - 1 && linqMethods.Contains(properies[i + 1]))
{
Child = type.GetProperty(properies[i]).GetValue(object1, null);
}
else if (linqMethods.Contains(properies[i]))
{
object1 = Child.Cast<object>().FirstOrDefault(); //for now works only with FirstOrDefault - Later it will be changed to work with ToList or other linq methods
type = object1.GetType();
}
else
{
if (linqMethods.Contains(properies[i]))
{
object1 = type.GetProperty(properies[i + 1]).GetValue(object1, null);
}
else
{
object1 = type.GetProperty(properies[i]).GetValue(object1, null);
}
type = object1.GetType();
}
}
value = object1.ToString(); //.StartDateTime.ToString();
}
return value;
}
I`m not sure if this is the best approach. Does anyone have a better suggestion, or maybe someone has already done something like this?
To shorten it: The idea is to make generic linq queries to database from a string like: "Case.Parties.FirstOrDefault.NameEn".
Your approach is very good. I have no doubt that it already works.
Another approach is using Expression Tree like #Egorikas have suggested.
Disclaimer: I'm the owner of the project Eval-Expression.NET
In short, this library allows you to evaluate almost any C# code at runtime (What you exactly want to do).
I would suggest you use my library instead. To keep the code:
More readable
Easier to support
Add some flexibility
Example
public string GetColumnValueByObjectByName(Expression<Func<TEntity, bool>> filter = null, string objectName = "", string dllName = "", string objectID = "", string propertyName = "")
{
string objectDllName = objectName + ", " + dllName;
Type type = Type.GetType(objectDllName);
Guid oID = new Guid(objectID);
object Entity = context.Set(type).Find(oID); // get Object by Type and ObjectID
var value = Eval.Execute("x." + propertyName, new { x = entity });
return value.ToString();
}
The library also allow you to use dynamic string with IQueryable
Wiki: LINQ-Dynamic
I am somewhat new to expression trees and I just don't quite understand some things.
What I need to do is send in a list of values and select the columns for an entity from those values. So I would make a call something like this:
DATASTORE<Contact> dst = new DATASTORE<Contact>();//DATASTORE is implemented below.
List<string> lColumns = new List<string>() { "ID", "NAME" };//List of columns
dst.SelectColumns(lColumns);//Selection Command
I want that to be translated into code like this (Contact is an entity using the EF4):
Contact.Select(i => new Contact { ID = i.ID, NAME = i.NAME });
So let's say I have the following code:
public Class<t> DATASTORE where t : EntityObject
{
public Expression<Func<t, t>> SelectColumns(List<string> columns)
{
ParameterExpression i = Expression.Parameter(typeof(t), "i");
List<MemberBinding> bindings = new List<MemberBinding>();
foreach (PropertyInfo propinfo in typeof(t).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (columns.Contains(propinfo.Name))
{
MemberBinding binding = Expression.Bind(propinfo, Expression.Property(i, propinfo.Name));
bindings.Add(binding);
}
}
Expression expMemberInit = Expression.MemberInit(Expression.New(typeof(t)), bindings);
return Expression.Lambda<Func<t, t>>(expMemberInit, i);
}
When I ran the above code I got the following error:
The entity or complex type 'Contact' cannot be constructed in a LINQ to Entities query.
I looked at the body of the query and it emitted the following code:
{i => new Contact() {ID = i.ID, NAME = i.NAME}}
I am pretty sure that I should be able to construct the a new entity because I wrote this line explicitly as a test to see if this could be done:
.Select(i => new Contact{ ID = i.ID, NAME = i.NAME })
This worked, but I need to construct the select dynamically.
I tried decompiling a straight query(first time I have looked at the low level code) and I can't quite translate it. The high level code that I entered is:
Expression<Func<Contact, Contact>> expression = z =>
new Contact { ID = z.ID, NAME = z.NAME };
Changing the framework used in the decompiler I get this code:
ParameterExpression expression2;
Expression<Func<Contact, Contact>> expression =
Expression.Lambda<Func<Contact, Contact>>
(Expression.MemberInit(Expression.New((ConstructorInfo) methodof(Contact..ctor),
new Expression[0]), new MemberBinding[] { Expression.Bind((MethodInfo)
methodof(Contact.set_ID), Expression.Property(expression2 = Expression.Parameter(typeof(Contact), "z"), (MethodInfo)
methodof(Contact.get_ID))), Expression.Bind((MethodInfo)
methodof(Contact.set_NAME), Expression.Property(expression2, (MethodInfo)
methodof(Contact.get_NAME))) }), new ParameterExpression[] { expression2
});
I have looked several places to try and understand this but I haven't quite gotten it yet. Can anyone help?
These are some places that I have looked:
msdn blog -- This is exactly what I want to do but my decopiled code soes not have Expression.Call.
msdn MemberInit
msdn Expression Property
stackoverflow EF only get specific columns -- This is close but this seems like it is doing the same thing as if i just use a select off of a query.
stackoverflow lambda expressions to be used in select query -- The answer here is exactly what I want to do, I just don't understand how to translate the decompiled code to
C#.
When I did it last time I projected result to not mapped class (not entity) and it worked, everything else was the same as in your code. Are you sure that not dynamic query like .Select(i => new Contact{ ID = i.ID, NAME = i.NAME }) works?
I am having a problem with the Dynamic Linq Library. I get a the following error "ParserException was unhandled by user code ')" or ','". I have a Dicitionary and I want to create a query based on this dictionary. So I loop through my dictionary and append to a string builder "PersonId = (GUID FROM DICTIONARY). I think the problem is were I append to PersonId for some reason I can't seem to convert my string guid to a Guid so the dynamic library don't crash.
I have tried this to convert my string guid to a guid, but no luck.
query.Append("(PersonId = Guid(" + person.Key + ")");
query.Append("(PersonId = " + person.Key + ")");
I am using VS 2010 RTM and RIA Services as well as the Entity Framework 4.
//This is the loop I use
foreach (KeyValuePair<Guid, PersonDetails> person in personsDetails)
{
if ((person.Value as PersonDetails).IsExchangeChecked)
{
query.Append("(PersonId = Guid.Parse(" + person.Key + ")");
}
}
//Domain service call
var query = this.ObjectContext.Persons.Where(DynamicExpression.ParseLambda<Person, bool>(persons));
Please help, and if you know of a better way of doing this I am open to suggestions.
For GUID comparison with dynamic linq use query properties and the Equals() method like in the provided sample.
var items = new[]
{
new { Id = Guid.Empty },
new { Id = Guid.NewGuid() },
new { Id = Guid.NewGuid() },
new { Id = Guid.NewGuid() }
};
var result = items.AsQueryable()
.Where("Id.Equals(#0)", Guid.Empty)
.Any();
Use a parameterized query, e.g.:
var query = this.ObjectContext.Persons.Where(
"PersonId = #1", new [] { person.Key } );
Did you try(notice the extra ')' ).
query.Append("(PersonId = Guid(" + person.Key + "))");