简体   繁体   English

使用User.Identity.GetUserId的ASP MVC应用程序用户为空

[英]ASP MVC Application User Null using User.Identity.GetUserId

Ok so I have a relationship between the ApplicationUser and QuestionResults, my models are as below, the userId nor the UserName is retrieved, but I really need the UserId setup as a foreignKey on the QuestionResults entity. 好的,所以我在ApplicationUser和QuestionResults之间有一个关系,我的模型如下所示,检索到了UserId或UserName,但是我确实需要UserId设置作为QuestionResults实体上的ForeignKey。

Any help is much appreciated the error that I am receiving is as below: 非常感谢任何帮助 ,我收到的错误如下:

An exception of type 'System.NullReferenceException' occurred in STRA.dll but was not handled in user code

Additional information: Object reference not set to an instance of an 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 the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

    }

Your code is equivalent to this:: 您的代码与此等效:

var user = qr.User;
user.Id = User.Identity.GetUserId();

If the QuestionResult was already linked to a User then you would not be changing which User is linked to the QuestionResult , you would be changing the Id of an existing User - and that is not allowed anyway. 如果QuestionResult已经链接到User ,那么你就不会改变其User链接到QuestionResult ,您将得到改变Id现有的User -这无论如何都不会允许的。

But the QuestionResult is not already linked to a User . 但是QuestionResult尚未链接到User qr.User is null - so you get a null reference exception. qr.Userqr.User因此您将获得null引用异常。

In general, life is much easier in Entity Framework if you add the foreign key to your model: 通常,如果将外键添加到模型中,则在Entity Framework中,生活会容易得多:

public class QuestionResult
{
   public string UserId { get; set; }

   public virtual ApplicationUser User { get; set; }
}

And now you can set the foreign key directly: 现在,您可以直接设置外键:

qr.UserId = User.Identity.GetUserId();

References: 参考文献:

Why does Entity Framework Reinsert Existing Objects into My Database? 为什么实体框架将现有对象重新插入到我的数据库中?

Making Do with Absent Foreign Keys 使用缺少的外键

So, do you wanna make foreing key for userid? 因此,您是否想为userid设置密钥?

You can do like that: 您可以这样做:

    public int UserRefID { get; set; }
    [ForeignKey("UserRefID")]
    public xxx UserID { get; set; } //data name like ApplicationUser

And this error appear coz you have some problem about models or data classes. 而且出现此错误是因为您对模型或数据类存在一些问题。

Set it as a string 将其设置为字符串

Model: 模型:

public ApplicationUser User { get; set; }
public string UserId { get; set; }

Controller: 控制器:

qr.UserId = User.Identity.GetUserId();

And worked perfectly, even created foreign keys, that easy. 并完美地工作,甚至创建外键也是如此。 Thanks so much! 非常感谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM