【问题标题】:ASP.NET - Get User ID For SeedingASP.NET - 获取种子用户 ID
【发布时间】:2020-05-17 13:54:31
【问题描述】:

我正在做一个代码优先的数据库,我想知道如何获取我存储的种子用户的 ID。

在这部分代码中,我正在创建用户。

         //Users
        List<ApplicationUser> applicationUsers = new List<ApplicationUser>();
        applicationUsers.Add(new ApplicationUser() { Email = "person1@test.test", UserName = "person1@test.test" });
        applicationUsers.Add(new ApplicationUser() { Email = "person2@test.test", UserName = "person2@test.test" });
        applicationUsers.Add(new ApplicationUser() { Email = "person3@test.test", UserName = "person3@test.test" });
        applicationUsers.Add(new ApplicationUser() { Email = "person4@test.test", UserName = "person4@test.test" });
        applicationUsers.Add(new ApplicationUser() { Email = "person5@test.test", UserName = "person5@test.test" });

        foreach (ApplicationUser user in applicationUsers)
        {
            manager2.Create(user, "qweQWE123!@#");
            manager2.AddToRole(user.Id, "RegisteredUser");
        }

效果很好,用户在我的数据库中,但是,我有一个使用 UserID 作为外键的模型。我如何通过在种子方法中创建这些用户来生成 GUID? 这是项目模型的模型,它使用用户 ID 外键。

        [Key]
    [Required]
    public int ItemID { get; set; }

    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public virtual ApplicationUser applicationUser { get; set; }

    [Required]
    public int ItemTypeID { get; set; }
    public ItemTypeModels ItemTypemodels { get; set; }

    [Required]
    [Range(0, int.MaxValue, ErrorMessage = "Quantity can't be negative")]
    public int ItemQuantity { get; set; }

    [Required]
    public int QualityID { get; set; }
    public QualityModels Qualitymodels { get; set; }

    [Required]
    [Range(1, double.MaxValue, ErrorMessage = "Price must be over 0")]
    public double ItemPrice { get; set; }

}

这就是我填写项目的方式

itemList.Add(new ItemModels() { ItemTypeID = 1, ItemPrice = 1.67,  ItemQuantity = 1, QualityID = 1, UserId="What do i put here?" });

【问题讨论】:

  • UserManager.Create不返回创建的用户吗?您应该能够从那里获取信息
  • @pinkfloydx33 UserManager.Create 返回 IdentityResult,如果创建成功与否,它只包含一个布尔值。
  • 你说得对,Create 会在传递给它的用户中填充 Id 属性(你在下一行使用它)......那你为什么不能直接使用它呢?

标签: c# asp.net asp.net-mvc


【解决方案1】:

在您的循环中,您已经在访问manager2.AddToRole() 中的 user.Id 属性。

播种item 的最简单方法是在该循环内创建项目对象,然后在添加所有项目后保存。

var itemList = new List<ItemModels>();

foreach (ApplicationUser user in applicationUsers)
{
   manager2.Create(user, "qweQWE123!@#");
   manager2.AddToRole(user.Id, "RegisteredUser");

   // use user.Id for ItemModel then add to list
   itemList.Add(new ItemModels() { UserId = user.Id, ItemTypeID = 1, ItemPrice = 1.67,  ItemQuantity = 1, QualityID = 1 });

}

// then save your items here
context.Items.AddToRange(itemList);
context.SaveChanges();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2012-10-20
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多