【问题标题】:DbSet.Find() doesn't work for Guid propertiesDbSet.Find() 不适用于 Guid 属性
【发布时间】:2020-01-09 05:45:04
【问题描述】:

我有两个模型

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

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

我正在 CHOICE Dbset 上执行 FInd 操作。

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

从上面一行 Find Operation 调用下面的方法。

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

我收到类似“调用'DbSet.Find'的位置0处的键值是'Expression>'类型的错误,它与'Guid'的属性类型不匹配”。请帮助我

【问题讨论】:

  • 想知道您是否找到了解决方案。它在我的本地机器上工作,但不在服务器上!

标签: c# .net asp.net-core entity-framework-core linq-expressions


【解决方案1】:

根据this文档,

EF Core DbSet&lt;TEntity&gt;.Find 不采用任何 predicate 而是采用实体的主键作为对象,如下所示:

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

此外,如果您想使用谓词查找而不是更新您的 Find 方法,如下所示:

public T Find(Expression<Func<T, bool>> predicate)
{
     var resultData = table.Where(predicate).FirstOrDefault();
     return resultData;
}

【讨论】:

    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2021-06-11
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    相关资源
    最近更新 更多