實體框架核心不適用於select(x => MyClass(x))

entity-framework-core

下面的Get(string _date)方法不起作用。我得到以下異常。我知道EFCore非常有限,但是這個例外無助於查看問題的確切位置。你能解釋一下導致這個例外的原因嗎?

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

一般承認的答案

您可以嘗試如下所示,然後告訴我們結果。

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

熱門答案

這個神秘的異常消息所說的是,在EF中,如果你想使用x來構造一個新對象,它必須採用new C { A = xB, ... } (其中C可以省略投影到匿名類型)。 EF不支持調用任意函數(包括構造函數),只支持某些特定功能,如調用屬性setter。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因