使用 EF Core 框架创建 SQLite 数据库(一对多连接)

问题描述 投票:0回答:1

我有像 MS 示例这样的模型(https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-many):

public class AdminModel
{
    [Display(Name = "Hostname")]
    public EndpointAdminModel? Hostname { get; set; }

    [Display(Name = "Username")]
    public required string Username { get; set; }

    public Boolean Enabled { get; set; }

    [DataType(DataType.Date)]
    public DateTime? EnabledUntil { get; set; }
    
    [DataType(DataType.Date)]
    public DateTime? Created { get; set; }

    public string? CreatedBy { get; set; }

    [DataType(DataType.Date)]
    public DateTime? Modified { get; set; }

    public string? ModifiedBy { get; set; }

}

和:

public class EndpointAdminModel
{
    [Key]
    [Display(Name = "Hostname")]
    public required string Hostname { get; set; }

    [Display(Name = "Administrator")]
    public ICollection<AdminModel>? Admin { get; set; }

    [Display(Name = "Enabled")]
    public Boolean Enabled { get; set; }

    [DataType(DataType.Date)]
    public DateTime? Created { get; set; }

    public string? CreatedBy { get; set; }

    [DataType(DataType.Date)]
    public DateTime? Modified { get; set; }

    public string? ModifiedBy { get; set; }

}

现在我想创建一对多连接:

modelBuilder.Entity<EndpointAdminModel>()
                .HasMany<AdminModel>(d => d.Admin)
                .WithOne(dm => dm.Hostname) 
                .HasForeignKey(d => new { d.Hostname, d.Username });

但这给了我错误: Microsoft.EntityFrameworkCore.dll 中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理:“无法将属性或导航“主机名”添加到“AdminModel”类型,因为属性或导航具有相同名称已存在于“AdminModel”类型中。'

当我用 .WithOne() 更改 .WithOne(dm => dm.Hostname) 时,我不再收到错误,但是

public BeyondTrustDBContext(DbContextOptions<BeyondTrustDBContext> options)
    : base(opAny idea what I am doing wrong?tions)
{
    Database.EnsureCreated();
}
由于我在模型中使用的属性,

失败了。我知道,SQLite 只支持少数,但我觉得对于我需要存储的 1000 条记录,SQlite 是最好的选择。

有人可以帮我吗?

编辑: 我想我必须添加一个真正的外键名称:

public required string Hostname { get; set; } // Foreign key

之后:

    modelBuilder.Entity<EndpointAdminModel>()
        .HasMany<AdminModel>(d => d.Admin)
        .WithOne(s => s.Host)
        .HasForeignKey(d => d.Hostname);

似乎有效。

c# sqlite entity-framework-core
1个回答
0
投票

如编辑部分所写:

我想我必须添加一个真正的外键名称:

公共必需字符串主机名{ get;放; } // 外键

之后:

modelBuilder.Entity<EndpointAdminModel>()
    .HasMany<AdminModel>(d => d.Admin)
    .WithOne(s => s.Host)
    .HasForeignKey(d => d.Hostname)
© www.soinside.com 2019 - 2024. All rights reserved.