如何在Asp.MVC中自动绑定当前用户

时间:2016-02-20 05:04:26

标签: c# asp.net-mvc

我正在研究和研究对象关系。我想将User对象作为属性包含在另一个对象中。 这是我的代码:

public class ToDo
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime DueDate { get; set; }
        public bool Done { get; set; }

        public ApplicationUser User { get; set; }
        public ToDo ParentTask { get; set; }
    }

据我所知,当我执行Create ToDo方法时,我可以搜索当前登录的用户ID,然后将该Id传递给ToDo对象。但我打算做的是在创建ToDo时自动将用户对象绑定到ToDo对象。我怎样才能实现这个目标? 我在互联网上搜索过,但还没有找到令人满意的答案。 任何帮助,将不胜感激。 感谢

2 个答案:

答案 0 :(得分:1)

我假设每个User都有一个ToDo列表...

因此...

public class ApplicationUser 
{
    // ... other properties
    public ICollection<ToDo> ToDos { get; set; }
}

现在每当你想添加一个新的Todo ......

user.ToDos.Add(todoItem);

如果您想以您展示的方式继续进行,那么您还需要public string UserId { get; set; }课程中的ToDo媒体资源。

创建新的ToDo项时,可以将调用者UserId填充到ToDo.UserId属性中。

请记住,这只会将项目分配给正确的用户,它不会从数据存储中获取具有所有属性的用户。为此,您必须首先从数据存储中明确请求用户。

答案 1 :(得分:1)

您可以创建构造函数并使用它们将User属性设置为所需用户,它可以是当前用户或使用它的id的任何用户。您只需要更改ToDo类。

public class ToDo
{
    [NotMapped]
    private ApplicationUserManager _userManager;

    [NotMapped]
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime DueDate { get; set; }
    public bool Done { get; set; }

    public ApplicationUser User { get; set; }
    public ToDo ParentTask { get; set; }

    public ToDo(ApplicationDbContext context)
    {
        // code to search user in to given context and set it to `User` Property
    }

    public ToDo(string userId)
    {
        // code to search user using UserManager by Id, can change it to include email, username or any other property and set it to `User` Property
    }

}

你也可以尝试这个,它获得当前用户。它将自动绑定到当前用户。

public ApplicationUser User
    {
        get
        {
            return UserManager.FindById(HttpContext.Current.User.Identity.GetUserId());
        }
        set
        {
            User = value;
        }
    }