Entity Framework matching a subset of an int - entity-framework

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()));

Related

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);

Autofac: Resolving contructor parameters based on single dependency

I have a scenario which I want autofac to resolve:
Here are my classes, I would have a factory method to take NetworkCredentials and return TopLevel object, this should internally resolve the InnerType1 and InnerType2 with the NetwokCredentials
public class TopLevel
{
public TopLevel(InnerType1 type1, InnerType2 type2)
{
}
}
public class InnerType1
{
public InnerType1(NetworkCredential credential)
{
}
}
public class InnerType2
{
public InnerType2(NetworkCredential credential)
{
}
}
Registration code > would something like this work ?
builder.Register<Func<NetworkCredential, TopLevel>>(c =>
{
var context = c.Resolve<IComponentContext>();
return (cred) => context.Resolve<TopLevel>(new TypedParameter(typeof(NetworkCredential), cred));
});
The crude approach could be to do resolve each contructor argument one by one inside resolution of TopLevel
No, that will not work since you are now instructing Autofac to provide a parameter value of type NetworkCredential to the TopLevel constructor which clearly requires two parameters of totally different types.
You will have to resolve InnerType1 and InnerType2 instances first and provide these to the TopLevel resolve. Something like this:
builder.Register<Func<NetworkCredential, TopLevel>>(c =>
{
var context = c.Resolve<IComponentContext>();
return (cred) => {
var i1 = context.Resolve<InnerType1>(TypedParameter.From(cred));
var i2 = context.Resolve<InnerType2>(TypedParameter.From(cred));
return context.Resolve<TopLevel>(TypedParameter.From(i1), TypedParameter.From(i2));
};
});
Note: I'm not seeing the whole picture of your system here, but if you feel that this is crude, perhaps you should look at revising your class hierarchy. IMO there's a faint smell of "too complex" in your code here, you require two different classes to be configured with the same data which makes me want to de-duplicate :)
Similar to Peter's answer, but slightly different flavor:
builder.Register<Func<NetworkCredential, TopLevel>>(c =>
{
var resolveInnerType1 = c.Resolve<Func<NetworkCredential, InnerType1>>();
var resolveInnerType2 = c.Resolve<Func<NetworkCredential, InnerType2>>();
var resolveTopLevel = c.Resolve<Func<InnerType1, InnerType2, TopLevel>>();
return (cred) => {
var i1 = resolveInnerType1(cred);
var i2 = resolveInnerType2(cred);
return resolveTopLevel(i1, i2);
};
});

EF4 Include() with Projection

I am trying to do a simple query which involves both eager loading and projection and am having problems. I am using CodeFirst CTP5 but I beleive that this issue affects straight EF4 as well.
Here is my initial query:
public List<ArticleSummary> GetArticles()
{
var articlesQuery = _db.Articles.Include(article => article.Category).Select(article => new ArticleSummary
{
Article = article,
CommentsCount = article.Comments.Count
});
return articlesQuery.ToList();
}
This results in the category property of article being null. If I take out the projection, it works just fine. After reading this, it seems to suggest that I need to do the include after the projection, so I changed the query to:
public List<ArticleSummary> GetArticles()
{
var articlesQuery = _db.Articles.Select(article => new ArticleSummary
{
Article = article,
CommentsCount = article.Comments.Count
});
articlesQuery = articlesQuery.Include(x => x.Article.Category);
return articlesQuery.ToList();
}
This results in an exception (see below) which is similar to this SO post.
"Unable to cast the type
'System.Linq.IQueryable1' to type
'System.Data.Objects.ObjectQuery1'.
LINQ to Entities only supports casting
Entity Data Model primitive types."
So, how do I do it?
You could try:
public List<ArticleSummary> GetArticles()
{
var articlesQuery = _db.Articles.Select(article => new
{
Article = article,
Category = article.Category
CommentsCount = article.Comments.Count
}
).ToList().
Select(
x => new ArticleSummary()
{
Article = x.Article,
CommentsCount = x.CommentsCount
}
);
return articlesQuery.ToList();
}

How to create and return an Expression<Func

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.