How to create and return an Expression<Func - asp.net-mvc-2

I Use entity Framework 4.
I would like to be able to create a function that return an Expression func that will be use in a lambda expression.
var ViewModel = _db.Suppliers.Select(model => new {
model,SupType = model.SupplierType.SupplierTypeTexts.Where( st => st.LangID == 1)
});
I would like to make this call like that
var ViewModel = _db.Suppliers.Select(model => new {
model,SupType = model.SupplierType.GetText()
});
My Partial class is:
public partial class SupplierType
{
public Expression<Func<SupplierTypeText, bool>> GetText()
{
return p => p.LangID == 1;
}
How can i perform this.

Easy. For example, Let's assume you have a Product table that is mapped to Products EntitySet in your context, now you want to pass a predicate and select a Product:
Expression<Func<Product, bool>> GetPredicate(int id) {
return (p => p.ProductID == id);
}
You can call GetPredicate() with a Product ID to filter based on that:
var query = ctx.Products.Where(GetPredicate(1)).First();
The point really is that you can always pass a Lambda Expression to where an Expression<T> is needed.
EDIT:
You should change your code like this:
var ViewModel = _db.Suppliers.Select(model => new {
model,
SupType = model.SupplierType.SupplierTypeTexts.Where(GetText())
});
public Expression<Func<SupplierTypeText, bool>> GetText() {
return (stt => stt.LangID == 1);
}

If you want to dynamically create compiled Expression at runtime (as opposed to ones hardcoded against a particular data model at compile time) you need to use the static methods on the Expression class.

Related

InvalidOperationException in where clause when attempting to create projection with Compile/Invoke

I've got a model and I want to build a simplified query model on top of it using projections.
Here we have 2 related 'derived' classes.
note - in the 2nd class ES_PROGRAMGUIDEDAYSCHEDULE, there are 2 implementations of of the projection, the uncommented explicit one works, the commented one out fails.
class ESP_CHANNEL
{
public string? name { get; set; }
public static Expression<Func<Channel, ESP_CHANNEL>> Projection
{
get
{
return x => new ESP_CHANNEL
{
name = x.LotIdLeafoftreepartNavigation.Leaf
};
}
}
}
class ES_PROGRAMGUIDEDAYSCHEDULE
{
public ESP_CHANNEL? ds_channel { get; set; }
public DateTime? ds_date { get; set; }
public static IQueryable<ES_PROGRAMGUIDEDAYSCHEDULE> Query(ModelContext context)
{
return context.Pgprogramguidedayschedules.Select(ES_PROGRAMGUIDEDAYSCHEDULE.Projection);
}
private static Expression<Func<Pgprogramguidedayschedule, ES_PROGRAMGUIDEDAYSCHEDULE>> Projection
{
get
{
return x => new ES_PROGRAMGUIDEDAYSCHEDULE
{
ds_date = x.PgdsIdDayscheduleNavigation.DsTxdate,
// If I explicitly instantiate an ESP_CHANNEL it works
ds_channel = new ESP_CHANNEL
{
name = x.PgdsIdDayscheduleNavigation.DsIdScheduleNavigation.SchIdChannelNavigation.LotIdLeafoftreepartNavigation.Leaf
}
// note THIS seemingly equivalent implementation via compile/invoke fails
//ds_channel = ESP_CHANNEL.Projection.Compile().Invoke(x.PgdsIdDayscheduleNavigation.DsIdScheduleNavigation.SchIdChannelNavigation)
};
}
}
}
If I then run this query like this.
var x =
(from schedule in ES_PROGRAMGUIDEDAYSCHEDULE.Query(ds)
where schedule.ds_channel.name == channel
&& schedule.ds_date == dt
select schedule).Take(1);
var ys = x.ToArray();
the explicit implementation in ES_PROGRAMGUIDEDAYSCHEDULE.Projection, works
ds_channel = new ESP_CHANNEL
{
name = x.PgdsIdDayscheduleNavigation.DsIdScheduleNavigation.SchIdChannelNavigation.LotIdLeafoftreepartNavigation.Leaf
}
whilst the seemingly equivalent implemention, where the instantiation of the ESP_CHANNEL is held in a the projection expression fails
ds_channel = ESP_CHANNEL.Projection.Compile().Invoke(x.PgdsIdDayscheduleNavigation.DsIdScheduleNavigation.SchIdChannelNavigation)
fails with
An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll
The LINQ expression 'DbSet<Pgprogramguidedayschedule>()
.LeftJoin(
inner: DbSet<Wondayschedule>(),
outerKeySelector: p => EF.Property<decimal?>(p, "PgdsIdDayschedule"),
innerKeySelector: w => EF.Property<decimal?>(w, "Oid"),
resultSelector: (o, i) => new TransparentIdentifier<Pgprogramguidedayschedule, Wondayschedule>(
Outer = o,
Inner = i
))
.LeftJoin(
inner: DbSet<Psischedule>(),
outerKeySelector: p => EF.Property<decimal?>(p.Inner, "DsIdSchedule"),
innerKeySelector: p0 => EF.Property<decimal?>(p0, "Oid"),
resultSelector: (o, i) => new TransparentIdentifier<TransparentIdentifier<Pgprogramguidedayschedule, Wondayschedule>, Psischedule>(
Outer = o,
Inner = i
))
.LeftJoin(
inner: DbSet<Channel>(),
outerKeySelector: p => EF.Property<decimal?>(p.Inner, "SchIdChannel"),
innerKeySelector: c => EF.Property<decimal?>(c, "LotIdLeafoftreepart"),
resultSelector: (o, i) => new TransparentIdentifier<TransparentIdentifier<TransparentIdentifier<Pgprogramguidedayschedule, Wondayschedule>, Psischedule>, Channel>(
Outer = o,
Inner = i
))
.Where(p => __Compile_0.Invoke(p.Inner).name == __channel_1 && p.Outer.Outer.Inner.DsTxdate == __dt_2)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
any ideas?
(the problem appears to be that its the where clause that fails to interpret the invoke correctly).
EDIT 1
note his query DOES execute correctly.
var x =
(from schedule in ES_PROGRAMGUIDEDAYSCHEDULE.Query(ds)
//where schedule.ds_channel.name == channel
//&& schedule.ds_date == dt
select schedule).Take(1);
so it appears that it is the where clause navigating via ds_channel that is causing the issue.
You can use LINQKit to make this query working. It needs just configuring DbContextOptions:
builder
.UseSqlServer(connectionString) // or any other provider
.WithExpressionExpanding(); // enabling LINQKit extension
Then you can inject your projection using LINQKit's Invoke method (but possible your query will be corrected also)
ds_channel = ESP_CHANNEL.Projection.Invoke(x.PgdsIdDayscheduleNavigation.DsIdScheduleNavigation.SchIdChannelNavigation)
Also you may find helpful this answer. It shows how to hide expression magic from end user.

Cleanest way to implement multiple parameters filters in a REST API

I am currently implementing a RESTFUL API that provides endpoints to interface with a database .
I want to implement filtering in my API , but I need to provide an endpoint that can provide a way to apply filtering on a table using all the table's columns.
I've found some patterns such as :
GET /api/ressource?param1=value1,param2=value2...paramN=valueN
param1,param2...param N being my table columns and the values.
I've also found another pattern that consists of send a JSON object that represents the query .
To filter on a field, simply add that field and its value to the query :
GET /app/items
{
"items": [
{
"param1": "value1",
"param2": "value",
"param N": "value N"
}
]
}
I'm looking for the best practice to achieve this .
I'm using EF Core with ASP.NET Core for implementing this.
Firstly be cautious about filtering on everything/anything. Base the available filters on what users will need and expand from that depending on demand. Less code to write, less complexity, fewer indexes needed on the DB side, better performance.
That said, the approach I use for pages that have a significant number of filters is to use an enumeration server side where my criteria fields are passed back their enumeration value (number) to provide on the request. So a filter field would comprise of a name, default or applicable values, and an enumeration value to use when passing an entered or selected value back to the search. The requesting code creates a JSON object with the applied filters and Base64's it to send in the request:
I.e.
{
p1: "Jake",
p2: "8"
}
The query string looks like:
.../api/customer/search?filters=XHgde0023GRw....
On the server side I extract the Base64 then parse it as a Dictionary<string,string> to feed to the filter parsing. For example given that the criteria was for searching for a child using name and age:
// this is the search filter keys, these (int) values are passed to the search client for each filter field.
public enum FilterKeys
{
None = 0,
Name,
Age,
ParentName
}
public JsonResult Search(string filters)
{
string filterJson = Encoding.UTF8.GetString(Convert.FromBase64String(filters));
var filterData = JsonConvert.DeserializeObject<Dictionary<string, string>>(filterJson);
using (var context = new TestDbContext())
{
var query = context.Children.AsQueryable();
foreach (var filter in filterData)
query = filterChildren(query, filter.Key, filter.Value);
var results = query.ToList(); //example fetch.
// TODO: Get the results, package up view models, and return...
}
}
private IQueryable<Child> filterChildren(IQueryable<Child> query, string key, string value)
{
var filterKey = parseFilterKey(key);
if (filterKey == FilterKeys.None)
return query;
switch (filterKey)
{
case FilterKeys.Name:
query = query.Where(x => x.Name == value);
break;
case FilterKeys.Age:
DateTime birthDateStart = DateTime.Today.AddYears((int.Parse(value) + 1) * -1);
DateTime birthDateEnd = birthDateStart.AddYears(1);
query = query.Where(x => x.BirthDate <= birthDateEnd && x.BirthDate >= birthDateStart);
break;
}
return query;
}
private FilterKeys parseFilterKey(string key)
{
FilterKeys filterKey = FilterKeys.None;
Enum.TryParse(key.Substring(1), out filterKey);
return filterKey;
}
You can use strings and constants to avoid the enum parsing, however I find enums are readable and keep the sent payload a little more compact. The above is a simplified example and obviously needs error checking. The implementation code for complex filter conditions such as the age to birth date above would better be suited as a separate method, but it should give you some ideas. You can search for children by name, and/or age, and/or parent's name for example.
I have invented and found it useful to combine a few filters into one type for example CommonFilters and make this type parseable from string:
[TypeConverter(typeof(CommonFiltersTypeConverter))]
public class CommonFilters
{
public PageOptions PageOptions { get; set; }
public Range<decimal> Amount { get; set; }
//... other filters
[JsonIgnore]
public bool HasAny => Amount.HasValue || PageOptions!=null;
public static bool TryParse(string str, out CommonFilters result)
{
result = new CommonFilters();
if (string.IsNullOrEmpty(str))
return false;
var parts = str.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
if (part.StartsWith("amount:") && Range<decimal>.TryParse(part.Substring(7), out Range<decimal> amount))
{
result.Amount = amount;
continue;
}
if (part.StartsWith("page-options:") && PageOptions.TryParse(part.Substring(13), out PageOptions pageOptions))
{
result.PageOptions = pageOptions;
continue;
}
//etc.
}
return result.HasAny;
}
public static implicit operator CommonFilters(string str)
{
if (TryParse(str, out CommonFilters res))
return res;
return null;
}
}
public class CommonFiltersTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string str)
{
if (CommonFilters.TryParse(str, out CommonFilters obj))
{
return obj;
}
}
return base.ConvertFrom(context, culture, value);
}
}
the request looks like this:
public class GetOrdersRequest
{
[DefaultValue("page-options:50;amount:0.001-1000;min-qty:10")]
public CommonFilters Filters { get; set; }
//...other stuff
}
In this way you reduce the number of input request parameters, especially when some queries don't care about all filters
If you use swagger map this type as string:
c.MapTypeAsString<CommonFilters>();
public static void MapTypeAsString<T>(this SwaggerGenOptions swaggerGenOptions)
{
swaggerGenOptions.MapType(typeof(T), () => new OpenApiSchema(){Type = "string"});
}

MongoDB C# Combining Fields

The Plan:
So now what I basically want is to take my propertys out of the class, let the user pick some and then pull a List with ONLY those propertys out of MongoDB.
The Code:
here is where the method starts:
private void DoStuffExecute(object obj)
{
Class class= new Class();
ExtractClass(class);
if (propList != null)
{
var result = classService.DoStuff(propList);
}
}
in "ExtractClass()" the Propertys are being pulled out of the Class.
void ExtractClass(object obj)
{
foreach (var item in obj.GetType().GetProperties())
{
propList.Add(item.Name);
}
}
and finally in "classService.DoStuff()" i try to set the "fields".
public List<class> DoStuff(List<string> Props)
{
try
{
var filter = Builders<class>.Filter.Empty;
var fields = Builders<class>.Projection.Include(x => x.ID);
foreach (var item in Props)
{
string str = "x.";
str += item.ToString();
fields = Builders<class>.Projection.Include(x => str);
fields = Builders<class>.Projection.Include(x => item);
}
var result = MongoConnectionHandler.MongoCollection.Find(filter).Project<class>(fields).ToList();
return result;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
var result = new List<class>();
return result;
}
}
when i run the programm it gives me an "Unable to determine the serialization information for x=> value"... since im giving it a string.
The Question:
Does anyone have an Idea how to repair the code above or even make the plan work in another way?
thank you.
First of all: you are using such code lines as : var filter = Builders<class>.Filter.Empty; It is not possible, because class is a reserved keyword in c# (https://msdn.microsoft.com/en-us/library/x53a06bb.aspx) I assume, it's your Model, and i will speak about it as about Model class.
Include Filter needs Expression as a parameter, not a string, you should construct is as a expression. That's the second thing. Third, you should combine your includes as a chain, So your part of creating Include Filter from string List should look like:
var filter = Builders<Model>.Filter.Empty;
var fields = Builders<Model>.Projection.Include(x => x.Id);
foreach (var item in Props)
{
var par = Expression.Parameter(typeof(Model));
var prop = Expression.Property(par, item);
var cast = Expression.Convert(prop, typeof(object));
var lambda = Expression.Lambda(cast, par);
fields = fields.Include((Expression<Func<Model, object>>)lambda);
}
I have all expresiions separate for better understanding: first you create Parameter (x=>), than you add property (x=>x.Property1), than you should cast it to object, and after all create Lambda Expression from it.
And now the last part: You don't need all of it, Include function could get jsut a string as a parameter. So you could instead of all expression call write this:
fields = fields.Include(item);

Entity Framework matching a subset of an int

I am implementing a search where I would like to partially match an entity's primary key. For example, if I would search for "123" it would return entities which have primary keys like:
12345
67123
91234
If this were a string, I'd attack it like this:
public PartialViewResult QuickSearch(string searchTerm)
{
var results = db.MyEntities.Where(x => x.myProperty.Contains(searchTerm));
return PartialView("QuickSearch_Results", results);
}
However I'm at a loss on the best way to do this for an int. I'm looking for something like this:
public PartialViewResult QuickSearch(int id)
{
var results = db.MyEntities.Where(x => x.myPropertyId.Contains(int));
return PartialView("QuickSearch_Results", results);
}
But obviously contains is not the right way to go. What would be a correct way of implementing this?
Totally wild and untested guess using the StringConvert method:
public PartialViewResult QuickSearch(int id)
{
string sId = id.ToString();
var results =
from x in db.MyEntities
where SqlFunctions.StringConvert((double)x.myPropertyId)
.Contains(sId)
select x;
return PartialView("QuickSearch_Results", results);
}
db.MyEntities.Where(x => x.myPropertyId.ToString().Contains(id.ToString()));

Stumped on Entity Framework & Lambda Expressions

I know currently the compiler is not liking this statement. Getting Error
Cannot convert lambda expression to delegate type 'System.Func<MyData.Models.SomeModels,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type
My Statement I'm passing to my Repository Class
var qry = repositoryClass.Find(c => c.Categories.Where(d => d.CategoryParentID == typeID));
Repository Class Find Method
public IEnumerable<SomeModels> Find(Func<SomeModels, bool> exp)
{
return (from col in _db.SomeModels where exp select col);
}
To work with EF you need an Expression<...>, applied (as a predicate) with Where:
public IEnumerable<SomeModels> Find(Expression<Func<SomeModels, bool>> exp)
{
return _db.SomeModels.Where(exp);
}
You'd then call that as:
var qry = repositoryClass.Find(c => c.CategoryParentID == typeID);
The lambda is then translated into an Expression<...>.
If your setup is more complex, please clarify.
I just added a method in my Repository Class
public IEnumerable<Models> GetByCategory(int categoryID)
{
var qry = _db.ModelCategories.Where(p => p.CategoryID == categoryID).First();
qry.Models.Load();
return qry.Models;
}
I'm guessing because it needs to be loaded this is the best way to go.