How to include a navigation property without selecting a new Model?

Viewed 229

Well, I was basicaly trying this:

_dbContext.BarcodeEvents.Include(e => e.BarcodeType).ToList();

Now I am expecting that I get a list of BarcodeEvents where the navigation property BarcodeType is set. The problem is, that BarcodeType is null. Then I configured EF Core to output the generated query, and figured out, it simple ignores the join.

First I thought, I have some error in the configuration of my navigation property, but then I realised, it is working when materializing it into a new model:

_dbContext.BarcodeEvents.Include(e => e.BarcodeType).Select(e => new
{
    e.EventTimestamp, //root property also available
    e.BarcodeType.BarcodeTypeDescription // navigation property available in this case
    //...
}).ToList();

Is it possible to select the whole BarcodeEvents including the BarcodeType without creating a new model?

I tried this, but the navigation property is still null:

_dbContext.BarcodeEvents.Include(e => e.BarcodeType).Select(e => e).ToList();

Just for reference, here are my Entities:

public class BarcodeEvents
{
    [Column("EventID")]
    public Guid EventId { get; set; }

    [Column(TypeName = "datetime")]
    public DateTime EventTimestamp { get; set; }

    [Column("DeviceID")]
    public int DeviceId { get; set; }

    public byte DataType { get; set; }

    [ForeignKey(nameof(DataType))]
    public virtual BarcodeTypes BarcodeType { get; set; }

    public string RawData { get; set; }
    public string DataLabel { get; set; }
    public string DecodedBarcode { get; set; }
}

public class BarcodeTypes
{
    [Key]
    [Column("BarcodeTypeID")]
    public byte BarcodeTypeId { get; set; }

    [StringLength(50)]
    public string BarcodeTypeDescription { get; set; }
}
1 Answers

The problem was, I have a project with 2 Framework Versions (Entity Framework 6 and Entity Framework Core).

I was using the Include method from:

using System.Data.Entity

Instead of the correct one:

using Microsoft.EntityFrameworkCore
Related