【发布时间】:2021-05-26 15:42:37
【问题描述】:
我有一个带有实体的应用程序,其中每个用户都有一个 Inventory 对象
public class BattlegroundUser : IdentityUser
{
[Required]
public Inventory Inventory { get; set; } = new Inventory();
}
每个库存都有一个卡片列表,其中包含卡片模型
public class Inventory
{
public Inventory()
{
}
public Inventory(string inventoryId, List<Card> cards, string inventoryOfId)
{
InventoryId = inventoryId;
Cards = cards;
InventoryOfId = inventoryOfId;
}
[Key]
public string InventoryId { get; set; }
[Required]
public List<Card> Cards { get; set; } = new List<Card>();
[Required]
[ForeignKey("InventoryOf")]
public string InventoryOfId { get; set; }
[Required]
public BattlegroundUser InventoryOf { get; set; }
}
这是卡片模型
public class Card
{
public Card(string cardId, string name, int health, int attack, int defend, string inInventoryId)
{
CardId = cardId;
Name = name;
Health = health;
Attack = attack;
Defend = defend;
InInventoryId = inInventoryId;
}
[Key]
public string CardId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Health { get; set; } = 100;
[Required]
public int Attack { get; set; }
[Required]
public int Defend { get; set; }
[Required]
[ForeignKey("InInventory")]
public string InInventoryId { get; set; }
[Required]
public Inventory InInventory { get; set; }
}
我不确定此设置是否正确,但请查看我的 DbContext
public class BattlegroundContext : IdentityDbContext<BattlegroundUser>
{
public override DbSet<BattlegroundUser> Users { get; set; }
public DbSet<Card> Cards { get; set; }
public DbSet<Inventory> Inventories { get; set; }
public BattlegroundContext(DbContextOptions<BattlegroundContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<BattlegroundUser>()
.HasOne(inv => inv.Inventory);
builder.Entity<BattlegroundUser>()
.HasKey(c => c.Id);
builder.Entity<Inventory>()
.HasMany(i => i.Cards)
.WithOne(c => c.InInventory);
builder.Entity<Inventory>()
.HasOne(c => c.InventoryOf);
builder.Entity<Inventory>()
.HasKey(c => c.InventoryId);
builder.Entity<Card>()
.HasOne(inv => inv.InInventory);
builder.Entity<Card>()
.HasKey(c => c.CardId);
List<Card> DefaultCards = new List<Card>();
Card card1 = new Card("-1", "Bonnie", 1000, 1000, 1000, "1");
Card card2 = new Card("-2", "Bab", 100, 100, 100, "1");
Card card3 = new Card("-3", "Tom", 10, 10, 10, "1");
DefaultCards.Add(card1);
DefaultCards.Add(card2);
DefaultCards.Add(card3);
builder.Entity<Card>()
.HasData(DefaultCards);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
如您所见,我尝试将一些卡片播种到数据库中。 添加迁移和更新数据库运行良好,然后当我尝试创建新帐户时,我在 Register.cshtml.cs 中收到此错误消息
var result = await _userManager.CreateAsync(user, Input.Password);
无法跟踪“Inventory”类型的实体,因为其主键属性“InventoryId”为空。
我不确定为什么它没有为 Inventory 分配一个新的 Id
编辑:我使用的是 EF Core 5
编辑2:
这是整个动作:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new BattlegroundUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
【问题讨论】:
-
你能精确一下 EF 版本吗? EF Core 5?
-
是的,它是 EF Core 5 @Vernou
-
你能展示
BattlegroundUser类吗? -
这是我的帖子@Vernou 中的第一个示例
-
var 结果 = await _userManager.CreateAsync(user, Input.Password);你能展示整个动作吗?
标签: .net entity-framework orm mapping