【问题标题】:Blazor / C# / ASP.NET Core MVC: adding a list inside an objectBlazor / C# / ASP.NET Core MVC:在对象内添加列表
【发布时间】: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


    【解决方案1】:

    您可以简单地将导航属性创建为

    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 创建关系。

    【讨论】:

    • hm,太奇怪了,添加这个仍然没有使错误停止,它仍然要求导航属性,我很抱歉,因为我对此很陌生,但非常感谢你的回复,我会的也继续找,谢谢!
    猜你喜欢
    • 2021-03-25
    • 2020-08-09
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2022-01-17
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多