【发布时间】:2021-10-04 20:28:33
【问题描述】:
我正在尝试在对象 person 中添加一个列表
public class Person
{
[Key]
public int Id { get; set; }
public bool ShowPerson { get; set; } //To show this person on the main database for the client side
public int Age { get; set; }
public string Name { get; set;}
public List<UserText> ListOfTexts{ get; set; } //this list
}
public class UserText
{
public int Id { get; set; }
[Required]
public string Text { get; set; }
}
我正在尝试让我的对象能够读取我的对象 (Person) 内部的列表
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Person>().HasData(new Person
{
Id = 1,
ShowPerson = true,
Age = 12,
Name = "John",
ListOfTexts = new list<UserText>()
{
new UserText{ Id = 1, Text = "I want to keep things simple"},
new UserText{ Id = 2, Text = "I want to keep things clean"}
},
});
}
}
当我尝试迁移数据库时,出现以下错误:
无法添加实体类型“Person”的种子实体,因为它设置了导航“ListOfTexts”。要为关系播种,请将实体种子添加到“UserText”并指定外键值 {'PersonId'}。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看所涉及的属性值。
我该怎么做才能正确地做到这一点?
-
我希望用户在他们的数据(人)中手动添加/删除尽可能多的文本
-
在 blazor 的详细信息页面中显示所有文本
例子:
<div>
@foreach (var textline in Person.ListOfTexts)
{
<p>@textline.Text</p>
}
@*Rest Of Code*@
</div>
【问题讨论】:
标签: c# asp.net-core-mvc blazor dbcontext