【问题标题】:ApplicationUser ICollection member not being saved in DBApplicationUser ICollection 成员未保存在数据库中
【发布时间】:2015-09-07 02:22:13
【问题描述】:

我已经向 ApplicationUser 添加了一些属性,其中两个是 ICollection 的。 当我使用 Update-Database 时,它​​不会为这两个成员生成列。

那么,我在这里缺少什么?我想这是非常基本的。我习惯于在 Java 中使用 Hibernate,它会为元素集合生成一个新表。

一些代码示例 -

应用程序用户

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public byte[] UserImage { get; set; }

    public virtual ICollection<string> Interests { get; set; }

    public virtual ICollection<string> Friends { get; set; }

}

注册视图模型

public class RegisterViewModel
{
    [Required]
    [Display(Name = "Username")]
    public string UserName { get; set; }

    [Required]
    [StringLength(25)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(25)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Display(Name = "User Image")]
    public int UserImage { get; set; }

    [Required]
    [Display(Name = "Interests")]
    public virtual ICollection<string> Interests { get; set; }

    [Display(Name = "Friends")]
    public virtual ICollection<string> Friends { get; set; }

    //........

任务寄存器(RegisterViewModel 模型)

 public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser()
            {
                UserName = model.UserName,
                FirstName = model.FirstName,
                LastName = model.LastName,
                Interests = model.Interests,
                Friends = model.Friends
            };

            HttpPostedFileBase file = Request.Files["file"];
            byte[] imgBytes = null;

            BinaryReader reader = new BinaryReader(file.InputStream);
            imgBytes = reader.ReadBytes(file.ContentLength);

            user.UserImage = imgBytes;


            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            //............

【问题讨论】:

    标签: c# .net entity-framework asp.net-mvc-4 asp.net-mvc-5


    【解决方案1】:

    您需要为您的收藏品建模。您可以多对多或一对多。

    // many to many
    public class Interest
    {
        public int InterestId { get; set; }
        public string InterestDesc { get; set; } // field can't match class name
    }
    
    // one to many
    public class Interest
    {
        public int UserId { get; set; }  // Make primary key the FK into application user
        public string InterestDesc { get; set; } // field can't match class name
    }
    

    然后更改您的收藏

    public virtual ICollection<Interest> Interests { get; set; }
    

    不要忘记将 DbSet 添加到上下文中。对 Friends 和其他字符串集合重复此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 2015-11-11
      • 2013-10-16
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      相关资源
      最近更新 更多