简体   繁体   中英

C# Entity Framework Core .Include() issue

I'm having a problem with the entity framework's "Include()" function

Framework used: .NET Core 3.1 with Entity Framework Core 3.1.5

These are my entities

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

so I launch this query:

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

the result of the query is as follows:

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

what I don't understand is why the "Include(j => j.EntityB)" does not return the EntityB field correctly valued

When I tried to build a data model with the entities provided in question, I encountered a compilation error at Index attribute.

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

Turns out entity framework 6 libraries used to have that attribute, but the question talks about entity framework core. So I just removed the Index attribute and moved it to OnModelCreating method to mimic similar behavior.

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

With that in place,I applied code first approach to generate the db and ran the program. Upon execution, ef core generated proper query:

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)

Hope it helps in resolving your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM