我有一个数据库,在名为 Bets
的表中的几行中模拟了数据,方法是用数字 1
填充前四行,然后用数字填充后四行编号为 2
的行。有一个 Team
表,其中的团队行对应于 ID 1
和 2
。
我将 .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
Bet
和 Team
之间的关系必须是多对多。虽然使用 Fluent API,您告诉 EF Core 将其视为一对一,因此在开始处理数据时会感到困惑 - 实际行为并不重要,显然这是您获得的奇怪数据,最好是它应该是一个异常(exception),但无论如何,EF Core 中还有很多东西等待实现,所以我们可以接受。
话虽如此,只需将 .WithOne()
更改为 .WithMany()
即可。问题解决了。
关于sqlite - EF Core 中每隔一个数据行都有一个空关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51174790/