sqlite - EF Core 中每隔一个数据行都有一个空关系

标签 sqlite .net-core entity-framework-core

我有一个数据库,在名为 Bets 的表中的几行中模拟了数据,方法是用数字 1 填充前四行,然后用数字填充后四行编号为 2 的行。有一个 Team 表,其中的团队行对应于 ID 12

我将 .NET Core 2.1.0 和 EF Core 2.1.0 与 SQLite 数据库结合使用。有一个类 Bet 与类 Team 具有多对一关系。它们看起来如下:

public class Bet
{
    public int Id { get; set; }

    public int TeamId { get; set; }
    public Team Team { get; set; }
}

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
}

为了访问数据,我使用以下语法:

public class BettingDbContext : DbContext
{
    public BettingDbContext(DbContextOptions<BettingDbContext> options)
        : base(options) { }

    public virtual DbSet<Bet> Bets { get; set; }
    public virtual DbSet<Team> Teams { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Bet>(entity =>
        {
            entity.ToTable("Bets");
            entity.HasIndex(e => e.Id)
                .IsUnique();
            entity.HasOne(b => b.Team)
                  .WithOne();
        });

        modelBuilder.Entity<Team>(entity =>
        {
            entity.ToTable("Teams");
            entity.HasIndex(e => e.Id)
                .IsUnique();
        });
    }
}

当我返回结果时,每隔行都会将 null 设置为其关系属性 Team。以下是立即窗口的一些输出:

> bets[0].Team
(null)
> bets[1].Team
{betting.DAL.Primitives.Team}
    Id: 1
    Name: "Uruguay"
> bets[2].Team
(null)
> bets[3].Team
{betting.DAL.Primitives.Team}
    Id: 1
    Name: "Uruguay"
> bets[4].Team
(null)
> bets[5].Team
{betting.DAL.Primitives.Team}
    Id: 2
    Name: "Russia"
> bets[6].Team
(null)
> bets[7].Team
{betting.DAL.Primitives.Team}
    Id: 2
    Name: "Russia"
> 

有什么想法可能会导致这种情况吗?

最佳答案

根据

filling the first four rows with the number 1 and the next four rows with the number 2

BetTeam 之间的关系必须是多对多。虽然使用 Fluent API,您告诉 EF Core 将其视为一对一,因此在开始处理数据时会感到困惑 - 实际行为并不重要,显然这是您获得的奇怪数据,最好是它应该是一个异常(exception),但无论如何,EF Core 中还有很多东西等待实现,所以我们可以接受。

话虽如此,只需将 .WithOne() 更改为 .WithMany() 即可。问题解决了。

关于sqlite - EF Core 中每隔一个数据行都有一个空关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51174790/

相关文章:

c# - 如何根据条件按 1 个表达式或 2 个表达式排序?

c# - 如何放弃对 EF Core 中上下文的更改

python - 使用 Python 连接字典值时如何只用引号括起字符串?

android - SQLite 选择今天和前一天的所有记录

c# - 如何在使用 '.NETFramework,Version=v4.5.2' 的项目中安装 System.Drawing.Common?

asp.net - 在 IIS 上使用 .NET Core 运行 ASP.NET 5 (MVC 6)

c# - Entity Framework 返回的列表为空

ios - 选择特定月份和年份的数据 sqlite xcode

SQLite ISO(即欧洲风格)周数

angular - 无法将 "dotnet new angular"创建的应用程序部署到 Azure