J'ai une table appelée 'GRNHDReturn' dans ma database. Je veux get le Max ReturnId de la table quand la table est vide. Comment puis-je faire ceci?
GRNHDReturn Database
public ssortingng getMax() { GRNHDReturn grh = new GRNHDReturn(); int max = 0; if ((context.GRNHDReturns.Max(p => p.ReturnId) == 0)) { max = 1; calculatemax = "RN" + max.ToSsortingng(); } else { max = context.GRNHDReturns.Max(p => p.ReturnId); int nextmax = max + 1; calculatemax = "RN" + nextmax.ToSsortingng(); } return calculatemax; }
public ssortingng getMax() { GRNHDReturn grh = new GRNHDReturn(); int? max = (from o in context.GRNHDReturns select (int?)o.ReturnId).Max(); if (max == 0 || max == null) { max = 1; calculatemax = "RN" + max.ToSsortingng(); } else { int? nextmax = max + 1; calculatemax = "RN" + nextmax.ToSsortingng(); } return calculatemax; }
Tu peux essayer ça.
Vous pouvez faire tout ce que vous voulez par ces lignes de code:
int max = 0; max = context.GRNHDReturns.Select(p => p.ReturnId) .DefaultIfEmpty().Max(); int nextmax = max + 1; calculatemax = "RN" + nextmax.ToSsortingng(); return calculatemax;
Par DefaultIfEmpty()
vous dites à EF de returnner 0
(la valeur par défaut pour int
) s'il n'y a pas d'loggings.