c# - Get the largest Value from table unless null -
i'm quite new c# , asp.net (and programming in general) , try simple exercises.
what trying do: build simple mvc app records have versions. is: given record, change via "edit"-view, record not overwritten. instead new record created (like new version). both, old , new record, have same itemid (which not primary key!), links them "semantically". in order know, record newer version, newer record has versionid +1 versionid of older one.
currently: i've started working on create-action. new record shall value of 1 it's versionid , itemid largest itemid in db plus 1 - unless there no record in db in case itemid shall 1.
the model:
namespace howtoupdate.models { public class itemwithversion { public int id { get; set; } public int itemnr { get; set; } public int versionnr { get; set; } public string name { get; set; } } }
the controller action:
[httppost] [validateantiforgerytoken] public actionresult create([bind(include = "id,name")] itemwithversion itemwithversion) { if (modelstate.isvalid) { // set itemnr int currentmaxitemnr = db.itemwithversions.max(i => i.itemnr); itemwithversion.itemnr = currentmaxitemnr + 1; // set versionnr itemwithversion.versionnr = 1; db.itemwithversions.add(itemwithversion); db.savechanges(); return redirecttoaction("index"); } return view(itemwithversion); }
problem: when run localhost/itemwithversion/create
, enter value name , submit, following error: "the cast value type 'system.int32' failed because materialized value null. either result type's generic parameter or query must use nullable type. source error: int currentmaxitemnr = db.itemwithversions.max(i => i.itemnr);
"
i tried:
// set itemnr int currentmaxitemnr = db.itemwithversions.max(i => i.itemnr); if (currentmaxitemnr == null) { itemwithversion.itemnr = 1; } else { itemwithversion.itemnr = currentmaxitemnr + 1; }
now error seems int currentmaxitemnr = db.itemwithversions.max(i => i.itemnr);
also int? currentmaxitemnr = db.itemwithversions.max(i => i.itemnr);
, var currentmaxitemnr = db.itemwithversions.max(i => i.itemnr);
won't good.
it's basic need help! :) thx.
you need make sure table not empty before calling max()
method. can use any()
method that.
int currentmaxitemnr = 0; if (db.itemwithversions.any()) { currentmaxitemnr = db.itemwithversions.max(i => i.itemnr); } itemwithversion.itemnr = currentmaxitemnr + 1; // set versionnr itemwithversion.versionnr = 1; db.itemwithversions.add(itemwithversion); db.savechanges();
Comments
Post a Comment