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

问题描述 投票:0回答:1

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

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

         //Users
        List<ApplicationUser> applicationUsers = new List<ApplicationUser>();
        applicationUsers.Add(new ApplicationUser() { Email = "[email protected]", UserName = "[email protected]" });
        applicationUsers.Add(new ApplicationUser() { Email = "[email protected]", UserName = "[email protected]" });
        applicationUsers.Add(new ApplicationUser() { Email = "[email protected]", UserName = "[email protected]" });
        applicationUsers.Add(new ApplicationUser() { Email = "[email protected]", UserName = "[email protected]" });
        applicationUsers.Add(new ApplicationUser() { Email = "[email protected]", UserName = "[email protected]" });

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

而且效果很好,用户都在我的数据库中,但是,我有一个模型,它使用UserID作为外键。我如何在种子方法中获得从创建这些用户中产生的GUID呢? 这就是项目模型的模型,使用UserID外键的模型。

        [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?" });
c# asp.net asp.net-mvc
1个回答
1
投票

在你的循环中,你已经访问了在 manager2.AddToRole().

最简单的方式来播种你的 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();
© www.soinside.com 2019 - 2024. All rights reserved.