efcore icon indicating copy to clipboard operation
efcore copied to clipboard

.Where() on a double depth .Include() causes error

Open JosephGarrone opened this issue 10 years ago • 9 comments

The following code:

var a = ProductionContext.Excavators;
var b = a.Include(q => q.Equipment);
var c = b.Include(q => q.Equipment.EquipmentType);
var d = c.Where(q => q.Equipment.Name == record.ResourceNumber);
var e = d.Where(q => q.Equipment.EquipmentType.Name == record.ResourceTypeReference);
var f = e.First();

Produces and error on var f = e.First() which is caused because var e = d.Where(...) fails with:

An unhandled exception of type 'System.InvalidCastException' occurred in EntityFramework.Relational.dll

Additional information: Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.ParameterExpression'.

Both record.ResourceNumber and record.ResourceTypeReference are string. Inspecting d, there is a single record with Equipment.EquipmentType.Name = "Excavator" and record.ResourceTypeReference = "Excavator".

IE: The query should go through completely fine, and in fact does go through completely fine if I modify d such as:

var d = c.Where(q => q.Equipment.Name == record.ResourceNumber).ToList();

Is this an issue with EF? Or am I abusing how it's supposed to work?

JosephGarrone avatar Jan 30 '16 02:01 JosephGarrone

@maumar this maybe fixed with your work going into RC2? If so, can you move it into the RC2 milestone

rowanmiller avatar Feb 10 '16 19:02 rowanmiller

Hello the same happens when doing:

var a = ProductionContext.Excavators;
var b = a.Include(q => q.Equipment);
var c = b.Include(q => q.Equipment.EquipmentType);
var d = c.Where(q => q.Equipment.Name.StartsWith("xxxx"));

pbarrios avatar Mar 03 '16 20:03 pbarrios

Any news on a workaround for this and/or if it will make it to RC2?

JosephGarrone avatar Mar 09 '16 01:03 JosephGarrone

@rowanmiller @JosephGarrone I will investigate this after I'm done with my current issue (likely tomorrow)

maumar avatar Mar 09 '16 03:03 maumar

@JosephGarrone in the meantime, could you provide some more information about the model you are using? Ideally please provide code for entity classes as well as DbContext.

maumar avatar Mar 09 '16 03:03 maumar

@maumar

Here are the models:


public class Excavator : Shared.DatabaseItem
{
    public bool ShiftReportRequired { get; set; }
    public bool ValidationRequired { get; set; }
    public bool ClientVehicle { get; set; }

    // Foreign Properties
    public int EquipmentID { get; set; }
    public Equipment.Equipment Equipment { get; set; }
    public int ModelID { get; set; }
    public ExcavatorModel Model { get; set; }

    [NotMapped]
    public List<ExcavatorShiftReportProduction> ProductionReports { get; set; }
    [NotMapped]
    public decimal TotalHours { get; set; }
}

public class Equipment : Shared.DatabaseItem
{
    [Column(TypeName = "varchar(MAX)")]
    public string Name { get; set; }
    public bool NoSite { get; set; }

    // Foreign Properties
    public int EquipmentTypeID { get; set; }
    public Types.EquipmentType EquipmentType { get; set; }
    public int? SiteID { get; set; }
    public Core.Site Site { get; set; }
}

public class EquipmentType : Shared.DatabaseItem
{
    [Column(TypeName = "varchar(MAX)")]
    public string Name { get; set; }
}

public class DatabaseItem : ITrackable, IUserTrackable
{
    public int ID { get; set; }
    [DefaultValue(1)]
    public int Revision { get; set; }
    public DateTime? TimeStamp { get; set; }

    // Foreign Properties
    public int? SubmittedByID { get; set; }
    [ForeignKey("SubmittedByID")]
    public Core.User SubmittedBy { get; set; }

    public void Update(DateTime TimeStamp, Core.User User)
    {
        this.Revision++;
        this.TimeStamp = TimeStamp;
        this.SubmittedByID = User.ID;
    }
}

As far as the DbContext goes, it's just your standard DbContext without anything special (Nothing in OnModelCreating(), only changes are on the SaveChanges(). I do not modify any models in code (IE: The default interpretation of my POCO's is fine)

JosephGarrone avatar Mar 09 '16 03:03 JosephGarrone

Here is the ProductionContext and its parent.

public class ProductionContext : CoreContext
{
    [FromServices]
    public SystemContext SystemContext { get; set; }

    // Equipment DB Sets
    public DbSet<Equipment.Equipment> Equipment { get; set; }

    // Types DB Sets
    public DbSet<Types.EquipmentType> EquipmentTypes { get; set; }

    // Vehicle DB Sets
    public DbSet<Vehicle.Excavator> Excavators { get; set; }

    // OTHER DBSETS REMOVED FOR BREVITY

    public ProductionContext() : base()
    {
        // Only fails when running `dnx ef migrations ...`
        try
        {
            SystemContext = (SystemContext)Startup.App.ApplicationServices.GetService(typeof(SystemContext));
        }
        catch (Exception)
        {

        }
    }

    public ProductionContext(DbContextOptions options) : base(options)
    {
        SystemContext = new SystemContext(options);
    }

    public static ProductionContext Initialise(ProductionContext context, Seed seed)
    {
        context.SystemContext = seed.SystemContext;
        return context;
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {

    }

    public override int SaveChanges()
    {
        // Update all entires marked as ITrackable
        ChangeTracker.Entries()
            .Where(q => q.State == EntityState.Added || q.State == EntityState.Modified)
            .Select(q => q.Entity).OfType<ITrackable>()
            .ForEach(q => q.Update(DateTime.UtcNow, SystemContext.GetCurrentUser()));

        return base.SaveChanges();
    }
}

public class CoreContext : DbContext
{
    public CoreContext(DbContextOptions options) : base(options)
    {

    }

    public CoreContext() : base()
    {

    }

    public IEnumerable<IEntityType> GetEntities()
    {
        return this.Model.GetEntityTypes();
    }

    public IEntityType GetEntity(string type)
    {
        return this.Model.FindEntityType(type);
    }

    public DbSet<DatabaseItem> GetDbSet(string type)
    {
        foreach (var dbset in this.GetType().GetProperties())
        {
            if (dbset.GetMethod.ReturnType.GenericTypeArguments.FirstOrDefault(q => q.FullName == type) != null)
            {
                return (DbSet<DatabaseItem>) dbset.GetValue(this);
            }
        }
        return null;
    }

    public IQueryable<dynamic> GetDbSetByType(string fullname)
    {
        Type targetType = Type.GetType(fullname);

        var model = GetType()
            .GetRuntimeProperties()
            .Where(o =>
                o.PropertyType.IsGenericType &&
                o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
                o.PropertyType.GenericTypeArguments.Contains(targetType))
            .FirstOrDefault();

        if (null != model)
        {
            return (IQueryable<dynamic>)model.GetValue(this);
        }

        return null;
    }
}

JosephGarrone avatar Mar 09 '16 03:03 JosephGarrone

@JosephGarrone @pbarrios The scenario works on our latest bits, so the solution will be available in RC2. Easiest workaround for now would be to break the query into two pieces:

var part1 = ProductionContext.Excavators
    .Where(q => q.Equipment.Name == record.ResourceNumber)
    .Where(q => q.Equipment.EquipmentType.Name == record.ResourceTypeReference)
    .First();

var part2 = ProductionContext.Excavators
    .Include(q => q.Equipment);
    .Include(q => q.Equipment.EquipmentType)
    .Where(q => q.ID == part1.ID)

maumar avatar Mar 10 '16 00:03 maumar

Thank you @maumar!!

pbarrios avatar Mar 10 '16 11:03 pbarrios