C#实体框架核心.include()问题

时间:2020-07-03 11:11:11

标签: c# entity-framework-core-3.1

我对实体框架的“ Include()”功能有疑问

使用的框架:.NET Core 3.1和Entity Framework Core 3.1.5

这些是我的实体

public class EntityA
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    
    [Required]
    [Index(IsUnique = true)]
    public int EntityBId { get; set; }

    [ForeignKey("EntityBId")]
    public EntityB EntityB { get; set; }

    [DefaultValue(false)]
    public bool IsConfirmed { get; set; }
}

public class EntityB
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }
    
    public string Description { get; set; }
}

所以我启动了这个查询:

public ICollection<EntityA> GetAll(string contextName)
{
    DbContext context = GetContext(contextName);

    ICollection<EntityA> collection = context.EntityAs
        .Include(j => j.EntityB)
        .Where(x => x.IsConfirmed)
        .ToList();

    return collection;
}

private DbContext GetContext(string contextName)
{
    string contextDbConnectionString = _secretsRepository.GetDbConnectionString(contextName);

    DbContextOptionsBuilder<DbContext> optionsBuilder = new DbContextOptionsBuilder<DbContext>();
    optionsBuilder.UseSqlServer(contextDbConnectionString);

    return new DbContext(optionsBuilder.Options);
}

查询结果如下:

{
    Id: 5
    IsConfirmed: true
    EntityB: null
    EntityBId: 72
}

我不明白的是为什么“ Include(j => j.EntityB)”不返回正确赋值的EntityB字段

1 个答案:

答案 0 :(得分:1)

当我尝试使用所提供的实体构建数据模型时,在Index属性时遇到了编译错误。

[Required]
[Index(IsUnique = true)]
public int EntityBId { get; set; }

找出了曾经具有该属性的实体框架6库,但问题是关于实体框架核心的问题。因此,我只是删除了Index属性并将其移至OnModelCreating方法以模仿类似行为。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<EntityA>().HasIndex(u => u.EntityBId).IsUnique();
}

有了这个,我采用了代码优先的方法来生成数据库并运行程序。执行后,ef核心生成了正确的查询:

SELECT [e].[Id], [e].[EntityBId], [e].[IsConfirmed], [e0].[Id], [e0].[Description], 
[e0].[Title]
FROM [EntityAs] AS [e]
INNER JOIN [EntityBs] AS [e0] ON [e].[EntityBId] = [e0].[Id]
WHERE [e].[IsConfirmed] = CAST(1 AS bit)

希望它有助于解决您的问题。