How do you create Expression<Func<T, T>> given the property names of T to map? - entity-framework

Here's what the required function would look like:
public static Expression<Func<T, T>> GetExpression<T>(string propertyNames) where T : class
{
var properties = propertyNames.Split(
new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries
).ToList();
//need help here
}
Currently I'm doing it like this:
_context.Questions.Select(q =>
new Question() {
QuestionId = q.QuestionId,
QuestionEnglish = q.QuestionEnglish
}
).ToList();
And I want to replace it with:
_context.Questions.Select(GetExpression<Question>("QuestionId, QuestionInEnglish")).ToList();
Any help would be greatly appreciated.

You can do it like this;
public static Func<T, T> GetExpression<T>(string propertyNames)
{
var xParameter = Expression.Parameter(typeof(T), "parameter");
var xNew = Expression.New(typeof(T));
var selectFields = propertyNames.Split(',').Select(parameter => parameter.Trim())
.Select(parameter => {
var prop = typeof(T).GetProperty(parameter);
if (prop == null) // The field doesn't exist
{
return null;
}
var xOriginal = Expression.Property(xParameter, prop);
return Expression.Bind(prop, xOriginal);
}
).Where(x => x != null);
var lambda = Expression.Lambda<Func<T, T>>(Expression.MemberInit(xNew, selectFields), xParameter);
return lambda.Compile();
}
Usage;
var list = new List<Question>{new Question{QuestionEnglish = "QuestionName",QuestionId = 1}};
var result = list.Select(GetExpression<Question>("QuestionId, QuestionEnglish"));

Related

System.Linq.Queryable.Except is not supported in Entity Framework Core

Please note this error message :
System.NotSupportedException: 'Could not parse expression
'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable
This overload of the method 'System.Linq.Queryable.Except' is
currently not supported.'
Is supported in newer versions of ef core?
my code :
var tuple = SearchBrand(searchTerm);
var result = GetExceptionsBrand(tuple.Item1, categoryId);
return Json(new
{
iTotalDisplayRecords = tuple.Item2,
iDisplayedBrand = result
.Skip(page * 10)
.Take(10)
.ToList(),
});
public async Task<Tuple<IQueryable<BrandDto>, int, int>>SearchBrand(string searchTerm)
{
var result = _context.Brands
.Where(c => c.IsDeleted == displayIsDeleted)
.WhereDynamic(searchTerm)
return new Tuple<IQueryable<BrandDto>, int, int>(result,
filteredResultsCount, totalResultsCount);
}
public IQueryable<BrandDto> GetExceptionsBrand(IEnumerable<BrandDto> filteredBrand, int categoryId)
{
var query = _context.CategoriesBrands.Where(x => x.CategoryId == categoryId);
var selectedList = new List<BrandDto>();
foreach (var item in query)
{
var cb = new BrandDto()
{
BrandDto_BrandId = item.BrandId
};
selectedList.Add(cb);
}
IQueryable<BrandDto> ExcpetList = filteredBrand.AsQueryable().Except(selectedList, new ComparerBrand());
return ExcpetList;
}

moq mongodb InsertOneAsync method

I am using Mongodb database with .net core. I just want to moq insert method that using mongodbContext. Here is what I am trying to do but it's not working:
public void InsertEventAsync_Test()
{
//Arrange
var eventRepository = EventRepository();
var pEvent = new PlanEvent
{
ID = "testEvent",
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
////Act
//mockEventContext.Setup(mr => mr.PlanEvent.InsertOne(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>()))
mockEventContext.Setup(s => s.PlanEvent.InsertOneAsync(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>())).Returns("sdad");
var result = eventRepository.InsertEventAsync(pEvent);
////Assert
result.Should().NotBeNull();
}
Below is the method that I need to Moq:
public EventRepository(IFMPContext eventContext)
{
_eventContext = eventContext;
}
public async Task<string> InsertEventAsync(Model.EventDataModel.PlanEvent eventobj)
{
eventobj._id = ObjectId.GenerateNewId();
eventobj.CreatedDateTime = DateTime.UtcNow.ToString();
try
{
_eventContext.PlanEvent.InsertOne(eventobj);
return eventobj.ID;
}
catch (Exception ex)
{
string x = ex.Message;
}
return "";
}
Assuming
public class EventRepository {
private readonly IFMPContext eventContext;
public EventRepository(IFMPContext eventContext) {
this.eventContext = eventContext;
}
public async Task<string> InsertEventAsync(Model.EventDataModel.PlanEvent eventobj) {
eventobj._id = ObjectId.GenerateNewId();
eventobj.CreatedDateTime = DateTime.UtcNow.ToString();
try {
await eventContext.PlanEvent.InsertOneAsync(eventobj);
return eventobj.ID;
} catch (Exception ex) {
string x = ex.Message;
}
return "";
}
}
You need to configure the test to support the async nature of the method under test
public async Task InsertEventAsync_Test()
{
//Arrange
var expected = "testEvent";
var pEvent = new PlanEvent {
ID = expected,
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
var mockEventContext = new Mock<IFMPContext>();
mockEventContext
.Setup(_ => _.PlanEvent.InsertOneAsync(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>()))
.ReturnsAsync(Task.FromResult((object)null));
var eventRepository = new EventRepository(mockEventContext.Object);
//Act
var actual = await eventRepository.InsertEventAsync(pEvent);
//Assert
actual.Should().NotBeNull()
actual.Should().Be(expected);
}
The test method definition needed to be updated to be asynchronous to allow the method under test to be awaited. The mock dependency also needed to be setup in such a way to allow the async flow to continue as expected when invoked.
#Nkosi Thanks a lot for your help. Finally i found the way. i was missing extra moq param It.IsAny<System.Threading.CancellationToken>() below is the working test
public void InsertEventAsync_Test()
{
//Arrange
var eventRepository = EventRepository();
var pEvent = new PlanEvent
{
ID = "testEvent",
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
////Act
mockEventContext.Setup(s => s.PlanEvent.InsertOne(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>(),It.IsAny<System.Threading.CancellationToken>()));
var result = eventRepository.InsertEventAsync(pEvent);
////Assert
result.Should().NotBeNull();
Assert.AreEqual(pEvent.ID, result);
}

Entity framework ordering using reflection

I have an extension method for ordering, the sortExpression can be something like "Description" or "Description DESC", it is working perfectly for columns at the same table:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortExpression)
{
if (source == null)
throw new ArgumentNullException("source");
if (string.IsNullOrEmpty(sortExpression))
return source;
var parts = sortExpression.Split(' ');
var isDescending = false;
var propertyName = "";
var type = typeof(T);
if (parts.Length > 0 && parts[0] != "")
{
propertyName = parts[0];
if (parts.Length > 1)
isDescending = parts[1].ToLower().Contains("esc");
var prop = type.GetProperty(propertyName);
if (prop == null)
throw new ArgumentException(string.Format("No property '{0}' on type '{1}'", propertyName, type.Name));
var funcType = typeof(Func<,>)
.MakeGenericType(type, prop.PropertyType);
var lambdaBuilder = typeof(Expression)
.GetMethods()
.First(x => x.Name == "Lambda" && x.ContainsGenericParameters && x.GetParameters().Length == 2)
.MakeGenericMethod(funcType);
var parameter = Expression.Parameter(type);
var propExpress = Expression.Property(parameter, prop);
var sortLambda = lambdaBuilder
.Invoke(null, new object[] { propExpress, new ParameterExpression[] { parameter } });
var sorter = typeof(Queryable)
.GetMethods()
.FirstOrDefault(x => x.Name == (isDescending ? "OrderByDescending" : "OrderBy") && x.GetParameters().Length == 2)
.MakeGenericMethod(new[] { type, prop.PropertyType });
var result = (IQueryable<T>)sorter
.Invoke(null, new object[] { source, sortLambda });
return result;
}
return source;
}
Working Example:
var query = db.Audit.Include("AccessLevel").AsQueryable();
query = query.OrderBy("Description");
Please note that the "Description" column exists at the same table "Audit".
What I'm trying to do is to sort by a column in a relation table:
Like the following
var query = db.Audit.Include("AccessLevel").AsQueryable();
query = query.OrderBy("AccessLevel.Name");
Which is equivalent to:
query = query.OrderBy(o => o.AccessLevel.Name);
What is the required modification on my extension method ?
I solved it by using the following code:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, parts[0], "OrderBy");
}
public static IQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenBy");
}
public static IQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
{
if (source == null)
throw new ArgumentNullException("source");
if (string.IsNullOrEmpty(property))
return source;
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach (string prop in props)
{
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IQueryable<T>)result;
}

sorting xtext AST through quickfix

I've Been Trying to change the order of nodes through quickfix, but something is wrong.
Here's my code in xtend:
#Fix(org.xtext.custom.conventions.validation.ConventionsValidator::CONVENTION_NOT_ORDERED)
def fixFeatureName( Issue issue, IssueResolutionAcceptor acceptor){
acceptor.accept(issue, 'Sort', "Sort '" + issue.data.head + "'", null)[
element, context |
var gr=(element as Greeting)
if (gr.name === null || gr.name.length === 0)
return;
var econt=gr.eContainer.eContents
var comparator = [ EObject obj1, EObject obj2 |
var o1 = (obj1 as Greeting)
var o2 = (obj2 as Greeting)
return o1.name.compareTo(o2.name)
]
ECollections::sort(econt, comparator)
]
}
No exception is being thrown to console, in debug I found an UnsupportedOperationException is thrown and handled by xtext.
I suspect that EList is immutable.
So how can I sort the AST?
(Here is the generated code: )
#Fix(ConventionsValidator.CONVENTION_NOT_ORDERED)
public void fixFeatureName(final Issue issue, final IssueResolutionAcceptor acceptor) {
String[] _data = issue.getData();
String _head = IterableExtensions.<String>head(((Iterable<String>)Conversions.doWrapArray(_data)));
String _plus = ("Sort \'" + _head);
String _plus_1 = (_plus + "\'");
final ISemanticModification _function = new ISemanticModification() {
public void apply(final EObject element, final IModificationContext context) throws Exception {
Greeting gr = ((Greeting) element);
boolean _or = false;
String _name = gr.getName();
boolean _tripleEquals = (_name == null);
if (_tripleEquals) {
_or = true;
} else {
String _name_1 = gr.getName();
int _length = _name_1.length();
boolean _tripleEquals_1 = (Integer.valueOf(_length) == Integer.valueOf(0));
_or = (_tripleEquals || _tripleEquals_1);
}
if (_or) {
return;
}
EObject _eContainer = gr.eContainer();
EList<EObject> econt = _eContainer.eContents();
final Function2<EObject,EObject,Integer> _function = new Function2<EObject,EObject,Integer>() {
public Integer apply(final EObject obj1, final EObject obj2) {
Greeting o1 = ((Greeting) obj1);
Greeting o2 = ((Greeting) obj2);
String _name = o1.getName();
String _name_1 = o2.getName();
return _name.compareTo(_name_1);
}
};
Function2<EObject,EObject,Integer> comparator = _function;
final Function2<EObject,EObject,Integer> _converted_comparator = (Function2<EObject,EObject,Integer>)comparator;
ECollections.<EObject>sort(econt, new Comparator<EObject>() {
public int compare(EObject o1,EObject o2) {
return _converted_comparator.apply(o1,o2);
}
});
}
};
acceptor.accept(issue, "Sort", _plus_1, null, _function);
}
thanks!
Sorting a temporary collection which will then replace econt didn't work. but I managed to solve it in a different way.
so one solution was to force a cast of eContainer as it's runtime element (which is Model), and then getting a list with it's getGreetings getter, and with that element the sorting works, but I didn't want to involve non-generic code, for technical reasons.
So after a lot of experiments I finally found that element without involving any other elements or keywords from the grammar:
var econt = (gr.eContainer.eGet(gr.eContainingFeature) as EObjectContainmentEList<Greeting>)
and that is exactly what was looking for. Sorting is successful!
Here's the resulting Xtend code (got rid of casing in the comperator as well):
#Fix(ConventionsValidator::CONVENTION_NOT_ORDERED)
def fixFeatureName(Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue, 'Sort', "Sort '" + issue.data.head + "'", null) [
element, context |
var gr = (element as Greeting)
if (gr.name === null || gr.name.length === 0)
return;
var econt = (gr.eContainer.eGet(gr.eContainingFeature) as EObjectContainmentEList<Greeting>)
var comparator = [ Greeting o1, Greeting o2 |
return o1.name.compareTo(o2.name)
]
ECollections::sort(econt, comparator)
]
}
and the generated java:
#Fix(ConventionsValidator.CONVENTION_NOT_ORDERED)
public void fixFeatureName(final Issue issue, final IssueResolutionAcceptor acceptor) {
String[] _data = issue.getData();
String _head = IterableExtensions.<String>head(((Iterable<String>)Conversions.doWrapArray(_data)));
String _plus = ("Sort \'" + _head);
String _plus_1 = (_plus + "\'");
final ISemanticModification _function = new ISemanticModification() {
public void apply(final EObject element, final IModificationContext context) throws Exception {
Greeting gr = ((Greeting) element);
boolean _or = false;
String _name = gr.getName();
boolean _tripleEquals = (_name == null);
if (_tripleEquals) {
_or = true;
} else {
String _name_1 = gr.getName();
int _length = _name_1.length();
boolean _tripleEquals_1 = (Integer.valueOf(_length) == Integer.valueOf(0));
_or = (_tripleEquals || _tripleEquals_1);
}
if (_or) {
return;
}
EObject _eContainer = gr.eContainer();
EStructuralFeature _eContainingFeature = gr.eContainingFeature();
Object _eGet = _eContainer.eGet(_eContainingFeature);
EObjectContainmentEList<Greeting> econt = ((EObjectContainmentEList<Greeting>) _eGet);
final Function2<Greeting,Greeting,Integer> _function = new Function2<Greeting,Greeting,Integer>() {
public Integer apply(final Greeting o1, final Greeting o2) {
String _name = o1.getName();
String _name_1 = o2.getName();
return _name.compareTo(_name_1);
}
};
Function2<Greeting,Greeting,Integer> comparator = _function;
final Function2<Greeting,Greeting,Integer> _converted_comparator = (Function2<Greeting,Greeting,Integer>)comparator;
ECollections.<Greeting>sort(econt, new Comparator<Greeting>() {
public int compare(Greeting o1,Greeting o2) {
return _converted_comparator.apply(o1,o2);
}
});
}
};
acceptor.accept(issue, "Sort", _plus_1, null, _function);
}

Return rows from stored procedure

I have this code:
public IEnumerable<SomeClass> GetAvalibleThingies(DateTime startDate, DateTime endDate, int categoryID)
{
if (_entities.Connection.State == System.Data.ConnectionState.Closed)
_entities.Connection.Open();
using (EntityCommand c = new EntityCommand("SomeEntities.GetAvalibleThingies", (EntityConnection)this._entities.Connection))
{
c.CommandType = System.Data.CommandType.StoredProcedure;
EntityParameter paramstartDate = new EntityParameter("startDate", System.Data.DbType.DateTime);
paramstartDate.Direction = System.Data.ParameterDirection.Input;
paramstartDate.Value = startDate;
c.Parameters.Add(paramstartDate);
........
var x = c.ExecuteReader();
return x as IEnumerable<SomeClass>;
};
But I can't get it to return a list of SomeClass. What's needed to do here? I use the entity framework 3.5sp1 one
/M
EntityDataReader is a class similar to SqlDataReader and should be handled in the similar way.
Instead of the lines
var x = c.ExecuteReader();
return x as IEnumerable;
should be something like
List list = new List();
using(EntityDataReader reader = c.ExecuteReader()) {
while(reader.Read()) {
SomeClass item = new SomeClass() {
};
list.Add(item);
}
}
return list;