c# - Changes to entity not registering -
i trying update list in 1 of entities. i'm doing:
var loggedinuserid = user.identity.getuserid(); var applicationdbcontext = new applicationdbcontext(); var x = request["groupcode"]; var affectedgroup = db.studentgroups.firstordefault(s => s.code == x); var groupid = affectedgroup.id; if (affectedgroup != null) { if (affectedgroup.studentids == null) { affectedgroup.studentids = new list<string>(); } if (affectedgroup.studentids.contains(loggedinuserid)) { tempdata["errormessage"] = "you member of group"; } else { affectedgroup.studentids.add(loggedinuserid); db.savechanges(); } }
here studentgroup model:
public class studentgroup { public int id { get; set; } [required(errormessage = "the group must have name.")] public string name { get; set; } [required(errormessage = "the code required.")] public string code { get;set; } public string description { get; set; } [display(name="members")] public ilist<string> studentids { get; set; } }
the problem studentids null when run in debugger, though when step through it, id added. i'm new asp.net mvc, please bear in mind.
i recommend using cross reference table handle functionality instead. have studentgroup model have id, code, name, , description fields; create xstudentsinstudentgroup table stores studentid , studentgroupid relate two.
the rest of code semi similar. can still groupid same way, once have can pull of student ids xstudentsinstudentgroup , use them however.
if(context.xstudentsinstudentgroup.any(x => groupid == x.studentgroupid && x.studentid == loggedinuserid)) { //already in } else { var xstudent = new xstudentsinstudengroup() { studentid = loggedinuserid studentgroupid = groupid }; context.insert(xstudent);//this depends on how add new records context.savechanges(); }
i how setting controllers. should have base creates , disposes new database context every action. or using statement clean context stated before.
--edit-- reason don't recommend way doing because doesn't seem make sense save list of ints , have update. if have working in other areas maybe issue have studentids object list of string , not ints.
Comments
Post a Comment