簡體   English   中英

Blazor / C# / ASP.NET 核心 MVC:在 object 中添加一個列表

[英]Blazor / C# / ASP.NET Core MVC: adding a list inside an object

我正在嘗試在 object 人員中添加一個列表

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; }        
}

我正在嘗試讓我的 object 能夠讀取我的 object(人)中的列表

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 創建關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM