I need to create a generic method to fetch some data related to another entity.
This is how my code looks like at the moment:
public static void InvalidateData<TEntity>(string foreignKey, int valueFK)
{
try
{
var key = typeof(TEntity).Name;
var adapter = (IObjectContextAdapter)EntityModelDataProvider.Database;
var objectContext = adapter.ObjectContext;
var container = objectContext.MetadataWorkspace.GetEntityContainer(
objectContext.DefaultContainerName, System.Data.Entity.Core.Metadata.Edm.DataSpace.CSpace);
var name = container.BaseEntitySets.Where((s) => s.ElementType.Name.Equals(key)).FirstOrDefault().Name;
string sqlQuery = String.Format(@"SELECT VALUE entity FROM [VW_{0}] WHERE entity.{1} = @foreignkey", name, foreignKey);
var query = objectContext.CreateQuery<TEntity>(sqlQuery, new ObjectParameter("foreignkey", valueFK));
var tmpResult = query.ToList();
}
catch (Exception)
{
throw;
}
}
And the error:
'entity.Average_FK' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near member access expression, line 1, column 58.
Generated query:
SELECT VALUE entity FROM [VW_Average_Client] WHERE entity.Average_FK = @foreignkey
I checked the Properties of the Entity and I do have one called "Average_FK".
Any idea how to achieve my goal?
UPDATE
I am trying to implement a generic where like this:
Expression<Func<TEntity, bool>> customFilter = entity => ComparePropertyValue<TEntity>(entity, foreignKey, valueFK);
var query = objectContext.CreateQuery<TEntity>("[" + name + "]").Where(customFilter);
....
private static bool ComparePropertyValue<TEntity>(TEntity entity, string property, object value)
{
try
{
PropertyInfo propertyInfo = typeof(TEntity).GetProperty(property);
return propertyInfo.GetValue(entity) == value;
}
catch (Exception)
{
throw;
}
}
And this exception:
LINQ to Entities does not recognize the method 'Boolean ComparePropertyValue[VW_Average_Client](XXX.EntityModel.VW_Average_Client, System.String, System.Object)' method, and this method cannot be translated into a store expression.