c# - ASP MVC Application User Null using User.Identity.GetUserId -
ok have relationship between applicationuser , questionresults, models below, userid nor username retrieved, need userid setup foreignkey on questionresults entity.
any appreciated error receiving below:
an exception of type 'system.nullreferenceexception' occurred in stra.dll not handled in user code additional information: object reference not set instance of object. on these lines of code: qr.user.id = user.identity.getuserid(); qr.user.username = user.identity.getusername();
models
public class questionresult { public questionresult() { datecreated = datetime.now; datemodified = datetime.now; } public int id { get; set; } public datetime? datecreated { get; set; } public datetime? datemodified { get; set; } public int questionscore { get; set; } //navigation properties public virtual applicationuser user { get; set; } //public icollection<categoryresult> categoryresult { get; set; } //public virtual category category { get; set; } [notmapped] public int categoryid { get; set; } public virtual question question { get; set; } public int questionid { get; set; } //public virtual category category { get; set; } //public int categoryid { get; set; } } public class applicationuser : identityuser { public string firstname { get; set; } public string surname { get; set; } public string industry { get; set; } public string globalregion { get; set; } public string currentsituation { get; set; } public int salesforcesize { get; set; } public bool isverified { get; set; } //navigation properties public virtual icollection<categoryresult> categoryresult { get; set; } public virtual icollection<questionresult> questionresult { get; set; } //public virtual icollection<report> report { get; set; } //public virtual icollection<surveyresult> surveyresult { get; set; } public virtual organisation organisation { get; set; } public int? organisationid { get; set; } public async task<claimsidentity> generateuseridentityasync(usermanager<applicationuser> manager) { // note authenticationtype must match 1 defined in cookieauthenticationoptions.authenticationtype var useridentity = await manager.createidentityasync(this, defaultauthenticationtypes.applicationcookie); // add custom user claims here return useridentity; } }
your code equivalent this::
var user = qr.user; user.id = user.identity.getuserid();
if questionresult
linked user
not changing user
linked questionresult
, changing id
of existing user
- , not allowed anyway.
but questionresult
not linked user
. qr.user
null - null reference exception.
in general, life easier in entity framework if add foreign key model:
public class questionresult { public string userid { get; set; } public virtual applicationuser user { get; set; } }
and can set foreign key directly:
qr.userid = user.identity.getuserid();
references:
Comments
Post a Comment