首页 > 解决方案 > 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”来查看涉及的属性值。

我该怎么做才能正确地做到这一点?

例子:

<div>
    @foreach (var textline in Person.ListOfTexts)
    {
        <p>@textline.Text</p>
    }

    @*Rest Of Code*@
</div>

标签: c#asp.net-core-mvcblazordbcontext

解决方案


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

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


推荐阅读