ASP.NET-获取播种的用户ID

我正在做一个代码优先的数据库,我想知道如何获取存储的种子用户的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?" });
评论
—抛弃
—抛弃

In your loop you're already accessing the user.Id property in manager2.AddToRole().

The easiest way to seed your item is create the item object inside that loop then save after adding all the items.

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();
点赞
评论