the Get(string _date) method below does not work. I get the following exception. I know EFCore is very limited but this exception does not help to see where the problem is exactly at. Can you please explain me what's causing this exception?
An unhandled exception occurred while processing the request.
ArgumentException: The given expression 'new EntryViewModel([x])' does not contain the searched expression '[x]' in a nested NewExpression with member assignments or a MemberBindingExpression.
Parameter name: fullExpression
InvokeMethod
TargetInvocationException: Exception has been thrown by the target of an invocation.
InvokeMethod
EntryController.cs
[HttpGet("{_date}")]
public async Task<IEnumerable<EntryViewModel>> Get(string _date)
{
DateTime date = DateTime.ParseExact(_date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
User user = await _userManager.GetUserAsync(HttpContext.User);
var Entries = _context.Entries.Include(x => x.Budget)
.Where(x => x.User.Id == user.Id && x.Date >= date && x.Date < date.AddDays(7))
.Select(x=> new EntryViewModel(x))
.ToList();
return Entries;
}
EntryViewModel.cs
public class EntryViewModel
{
public int Id { get; set; }
public int BudgetId { get; set; }
public string Date { get; set; }
public int Duration { get; set; }
public string UserId { get; set; }
public EntryViewModel(Entry entry)
{
Id = entry.Id;
BudgetId = entry.BudgetId;
Date = entry.Date.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture);
Duration = entry.Duration;
UserId = entry.UserId;
}
}
You can try as shown below then and let us know about the result.
var Entries = _context.Entries.Include(x => x.Budget)
.Where(x => x.User.Id == user.Id && x.Date >= date && x.Date < date.AddDays(7))
.Select(e=> new EntryViewModel
{
BudgetId=e.BudgetId,
Duration=e.Duration,
}).ToList();
What this cryptic exception message is saying is that in EF, if you want to use x
to construct a new object, it must be in the form new C { A = x.B, ... }
(where C
may be omitted to project to an anonymous type). EF does not support calling arbitrary functions (including constructors), only some specific functionality such as calling property setters is supported.