Only parameterless constructors and initializers are supported in LINQ to Entities

后端 未结 14 1321
暗喜
暗喜 2020-11-27 15:27

I have this error in this linq expression :

var naleznosci = (from nalTmp in db.Naleznosci
                              where nalTmp.idDziecko == idDziec
           


        
相关标签:
14条回答
  • 2020-11-27 16:12

    You can try to do the same, but using the methods of extension. What is the provider of the database use?

    var naleznosci = db.Naleznosci
                              .Where<TSource>(nalTmp => nalTmp.idDziecko == idDziec)
                              .Select<TSource, TResult>(
                                 delegate(TSource nalTmp) { return new Payments
                                 (
                                     nalTmp.Dziecko.Imie,
                                     nalTmp.Dziecko.Nazwisko,
                                     nalTmp.Miesiace.Nazwa,
                                     nalTmp.Kwota,
                                     nalTmp.RodzajeOplat.NazwaRodzajuOplaty,
                                     nalTmp.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
                                     nalTmp.DataRozliczenia,
                                     nalTmp.TerminPlatnosci
                                 ); })
                              .ToList();
    
    0 讨论(0)
  • 2020-11-27 16:20

    Sorry for being late to the party, but I after finding this, I thought this should be shared as it's the cleanest, fastest and also memory-saving implementation I could find.

    Adapted to your example, you'd write:

    public static IQueryable<Payments> ToPayments(this IQueryable<Naleznosci> source)
    {
      Expression<Func<Naleznosci, Payments>> createPayments = naleznosci => new Payments
      {
        Imie = source.Dziecko.Imie,
        Nazwisko = source.Dziecko.Nazwisko,
        Nazwa= source.Miesiace.Nazwa,
        Kwota = source.Kwota,
        NazwaRodzajuOplaty = source.RodzajeOplat.NazwaRodzajuOplaty,
        NazwaTypuOplaty = source.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
        DataRozliczenia = source.DataRozliczenia,
        TerminPlatnosci = source.TerminPlatnosci,
      };
    
      return source.Select(createPayments);
    }
    

    The big advantages here (as Damien Guard pointed out in the comments at the link) are:

    • Safes you from using initialization pattern on each occurrence.
    • Usage via var foo = createPayments(bar); as well as usage via myIQueryable.ToPayments() possible.
    0 讨论(0)
提交回复
热议问题