在我的 .net core 3.1 应用程序中,我想将属性封装在某个实体中:
public class Sample : AuditableEntity
{
public Sample(string name)
{
Name = name;
}
public int Id { get; }
public string Name { get; }
}
因此,当我想检查此类 Sample 是否已经存在时,我已经删除了所有公共设置器,因此在我的代码中某处
_context.Samples.Any(r => r.Name == name)
该行导致错误:System.InvalidOperationException: 'No suitable constructor found for entity type 'Sample'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'name' in 'Sample(string name)'.'
.
所以我添加了代码空构造器
public class Sample : AuditableEntity
{
public Sample() { } // Added empty constructor here
public Sample(string name)
{
Name = name;
}
public int Id { get; }
public string Name { get; }
}
现在该行导致错误:System.InvalidOperationException: 'The LINQ expression 'DbSet<Sample>
.Any(s => s.Name == __name_0)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
。
但是,如果我将私有集添加到Name
(或公共),那么一切正常(即使没有空构造函数)。
public class Sample : AuditableEntity
{
public Sample(string name)
{
Name = name;
}
public int Id { get; }
public string Name { get; private set; } // added setter, removed empty constructor
}
谁能解释我为什么需要这个setter,例如Id不需要那个setter。