c# - Blazor / C# / ASP.NET Core MVC:在对象内添加列表
问题描述
我正在尝试在对象 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; }
}
我试图让我的对象能够读取我的对象(人)内部的列表
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>
解决方案
您可以简单地将导航属性创建为
public class Person
{
public int PersonID { get; set; }
public bool ShowPerson { get; set; }
public int Age { get; set; }
public string Name { get; set;}
public virtual List<UserText> ListOfTexts{ get; set; }
}
public class UserText
{
public int UserTextID { get; set; }
[Required]
public string Text { get; set; }
}
有了这个,我希望没有问题,因为 .net 核心基于在 Person Model 中创建的导航属性 ListOfTexts 创建关系。
推荐阅读
- ruby-on-rails - 在 Rails 中为每个 GET 请求附加一个参数
- javascript - Javascript - 编写 js 插件时如何构建最小文件
- c++ - C++ 程序在迭代中变慢
- api - 如何根据窗口标题栏结束进程?
- python - pyGithub最大使用API调用率
- python - 使用 multiprocess.Process 创建进程以并行操作多个生成器,而不首先列出列表
- javascript - JS和正则表达式用于替换double = mark内的所有内容
- regex - 用于删除“|”的 Google Apps 脚本正则表达式 单引号,管道,单引号 - 导致超时
- javascript - Laravel Mix / Webpack:当我调用“npm run prod”时,它不会缩小 .scripts 但会缩小 .js
- c++11 - 使用接受 lambda 的模板函数重载