Can't use string.Format() in Anonymous Type - anonymous-types

I'm hoping to achieve something as follows:
var comboBoxItems = from state in states
select new
{
Key = state.Code,
Value = string.Format("{0} ({1})", state.Name, state.Code)
};
this.stateComboBox.DisplayMember = "Value";
this.stateComboBox.ValueMember = "Key";
this.stateComboBox.DataSource = new BindingSource(comboBoxItems, null);
However, it gives me the following error when it attempts to bind to the DataSource:
"LINQ to Entities does not recognize the method 'System.String
Format(System.String, System.Object, System.Object)' method, and this
method cannot be translated into a store expression."
Is there any way to include a method like string.Format() in the Anonymous Type?

var comboBoxItems = from state in states.ToList()
select new
{
Key = state.Code,
Value = string.Format("{0} ({1})", state.Name, state.Code)
};
You cannot use Format in LINQ 2 Entities as it cannot be translated to SQL. A call to ToList will cause the items to be loaded from DB and your format will now execute properly.

Related

Drools - extract value inside a map and assign - error : unable to resolve method using strict-mode

Thanks to #roddy for his answer to my query here
Copy pasting from earlier to set the context :
here is my data structure :
public class Premium{
private Map<String,Map<String,String>> valuesMap = new HashMap<String,Map<String,String>>();
public Map<String, Map<String, String>> getValuesMap() {
return valuesMap;
}
}
Sample values that will be present inside this 'valuesMap' :
Map<String,String> m1= new HashMap<String,String>();
m1.put("death","100");
m1.put("income","50");
valuesMap.put("Male",m1);
valuesMap.put("Female",m2);
....
Thanks to #Roddy now I can extract the map 'm1' embedded within 'valuesMap' for "Male"
rule "rule#7 testing me 001 "
when
// below line extracts 'valuesMap' from Premium object
$pr:Premium($masterMap:valuesMap)
// now have a handle to the embedded map for 'Male'
Map( $male: this["Male"] ) from $masterMap
// defining an object in which I want to populate the value from map obtained for male
$rulesResponse:RulesResponse();
then
System.out.println("rule#7 map " + $map);
// this is where in below code it is failing
$rulesResponse.abc = $innerMap.get("income");
end
when I am trying to extract the string from map against key 'income' and assign it to the 'RulesResponse' object it fails with :
[Error: unable to resolve method using strict-mode: java.lang.Object.get(java.lang.String)]
[Near : {... nse.abc = $innerMap.get("income"); ....}]
The response object is a simple POJO with getter and setter for attribute : abc
public class RulesResponse {
private String abc = "";
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
If I try and assign a hard coded value - it works and also reflects after the rule is executed
// this works
$rulesResponse.abc = "hard coded value";
When you get this["Male"] out of the map, it's an Object, not anything typed. It's basically due to type erasure -- Map<String, ?>.
You can get "income" out by doing Map( $income: this["income"]) from $male. Of course, now $income will too also be an Object so you'll need to cast it again. Could be as simple as a (String)$income on the right-hand side, or a $incomeStr: String() from $income on the left.
rule "Example"
when
$pr: Premium( $masterMap: valuesMap != null )
Map( $male: this["Male"] != null ) from $masterMap
Map( $income: this["income"] != null ) from $male
$rulesResponse: RulesResponse()
then
$rulesResponse.abc = (String)$income; // cast as necessary
end
We lose the nested type identity because of type erasure -- you've got a Map<String, ?> which becomes Map<String, Object> in practice.
Strongly suggest using a properly structured POJO instead of a Map as a rule input. Even if your actual code uses these nested maps (bad practice!), you should leverage a transform before calling the rules -- not only will your rules be a lot simpler and easier to work with, but they'll also be much more performant.
Even converting that inner map into an object will make things easier:
class GenderValues {
String death;
String income;
}
class Premium {
Map<String, GenderValues> valuesByGender;
}
Best practice would be to omit the Map entirely.

Postsharp introduce Attributes with Property Arguments

I am trying to achieve attribute introduction like here but my attributes have property arguments like: [Foo(Bar = "Baz")]
How do I correctly pass the arguments? I'm not copying the attributes from something else, so I don't think I can use CustomAttributeData?
You can set properties of your custom attributes by using ObjectConstruction.NamedArguments dictionary.
For example:
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
Type targetType = (Type) targetElement;
var objectConstruction =
new ObjectConstruction(typeof (MyCustomAttribute).GetConstructor(Type.EmptyTypes));
objectConstruction.NamedArguments["Bar"] = "Baz";
var introduceAttributeAspect = new CustomAttributeIntroductionAspect(objectConstruction);
yield return new AspectInstance(targetType, introduceAttributeAspect);
}

How do we convert a column from table to an arraylist using ormlite?

I'm trying to convert an entire column values into a arrayList using ormlite on android, is this possible, with direct api?
Using raw results i get close, but not quite:
GenericRawResults<String[]> rawResults =
getHelper().getMyProcessDao().queryRaw(
queryBuild.selectColumns("nid").prepareStatementString());
List<String[]> result = rawResults.getResults();
Hrm. I'm not sure this is what you want. However, one way to accomplish what you ask for specifically is through by using the RawRowMapper which can be passed to ORMLite's DAO method: dao.queryRaw(String, Rowmapper, String...).
Something like the following should work:
RawRowMapper<Integer> mapper = new RawRowMapper<Integer>() {
public Integer mapRow(String[] columnNames, String[] resultColumns) {
// maybe you should verify that there _is_ only 1 column here
// maybe you should handle the possibility of a bad number and throw
return Integer.parseInt(resultColumns[0]);
}
};
GenericRawResults<Integer> rawResults =
getHelper().getMyProcessDao().queryRaw(
queryBuild.selectColumns("nid").prepareStatementString(), mapper);
List<Integer> list = rawResults.getResults();

EF4.1 Code First: Stored Procedure with output parameter

I use Entity Framework 4.1 Code First. I want to call a stored procedure that has an output parameter and retrieve the value of that output parameter in addition to the strongly typed result set. Its a search function with a signature like this
public IEnumerable<MyType> Search(int maxRows, out int totalRows, string searchTerm) { ... }
I found lots of hints to "Function Imports" but that is not compatible with Code First.
I can call stored procedures using Database.SqlQuery(...) but that does not work with output parameters.
Can I solve that problem using EF4.1 Code First at all?
SqlQuery works with output parameters but you must correctly define SQL query and setup SqlParameters. Try something like:
var outParam = new SqlParameter();
outParam.ParameterName = "TotalRows";
outParam.SqlDbType = SqlDbType.Int;
outParam.ParameterDirection = ParameterDirection.Output;
var data = dbContext.Database.SqlQuery<MyType>("sp_search #SearchTerm, #MaxRows, #TotalRows OUT",
new SqlParameter("SearchTerm", searchTerm),
new SqlParameter("MaxRows", maxRows),
outParam);
var result = data.ToList();
totalRows = (int)outParam.Value;

returning an ObjectQuery<T> from the objectQuery using reflection

I have one method which is returning the object of ObjectQuery in this ObjectQuery object the type of object is ObjectQuery, now i want to include table in this object
using reflection, i called the method Include using reflection for this but i m getting the error can someone please tell me the error. here is the sample code.
ObjectQuery objTest = LoadEntitiy(entites,entityClassType);
public ObjectQuery LoadEntitiy(ClientEntities entities, Type entityClasstype)
{
PropertyInfo pi = entities.GetType().GetProperties().First(item => item.Name == entityClasstype.Name.ToString());
Object obj = pi.GetValue(entities, null);
Type objContext = obj.GetType();
return (ObjectQuery)obj;
}
now i m calling the method for including it using the reflection that is here
Type lstType = typeof(ObjectQuery<>);
Type constructedType = lstType.MakeGenericType(typeof(ObjectQuery<>));
MethodInfo addListItemMethod = constructedType.GetMethod("Include");
addListItemMethod.Invoke(objTest, new object[] {"tablename" });
It seems that you want to define a convention to always "Include" a certain set of data.
This convention is normally known as eager loading and there are alternatives like lazy loading.
EF 4.1 or greater already includes functionality to do this for you, see http://msdn.microsoft.com/en-us/library/gg715120(v=vs.103).aspx
Type lstType = typeof(ObjectQuery<>);
Type constructedType = lstType.MakeGenericType(typeof(T(which u want to send as parameter)));
MethodInfo addListItemMethod = constructedType.GetMethod("Include");
object objtest = addListItemMethod.Invoke(objTest, new object[] {"tblname" });
Now the objtest contains the all the table names which you want to include.