DbSet.Find() doesn't work for Guid properties

.net asp.net-core c# entity-framework-core linq-expressions

Question

I have two models

public class QChoice : ModelWithGuid
{
    [Required]
    public Guid? QId { get; set; }
}

public class ModelWithGuid
{
    [Key]
    public Guid Id { get; set; } = Guid.NewGuid();
}

I'm performing FInd opertion on CHOICE Dbset.

DataContext.QChoice.Find(choice => choice.QId.Value.Equals("Guid")).ToList();

From the above line Find Operation calls below method.

public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
  var resultData = table.Find(predicate);//table means QChoice DbSet
  yield return resultData;
}

I'm getting error like "The key value at position 0 of the call to 'DbSet.Find' was of type 'Expression>', which does not match the property type of 'Guid'".Please help me

1
0
1/9/2020 5:45:04 AM

Accepted Answer

According to this documenation,

EF Core DbSet<TEntity>.Find does not take any predicate rather it takes the primary key of the entity as object as follows:

var qChoice = DataContext.QChoice.Find(choice.QId);

Moreover if you want find with predicate than update your Find method as follows:

public T Find(Expression<Func<T, bool>> predicate)
{
     var resultData = table.Where(predicate).FirstOrDefault();
     return resultData;
}
1
1/9/2020 6:02:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow