我正在做一个代码优先的数据库,我想知道如何获取存储的种子用户的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?这是项目模型的模型,该模型使用用户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?" });
在循环中,您已经可以访问中的user.Id属性manager2.AddToRole()
。
播种的最简单方法item
是在该循环内创建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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句