In my .net core 3.1 application I wanted to encapsulate properties in some entity:
public class Sample : AuditableEntity
{
public Sample(string name)
{
Name = name;
}
public int Id { get; }
public string Name { get; }
}
So I've removed all public setters and because of that somewhere in my code when I want to check whether such Sample already exists
_context.Samples.Any(r => r.Name == name)
that line causes the error: 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)'.'
.
So I've added to code empty construtor
public class Sample : AuditableEntity
{
public Sample() { } // Added empty constructor here
public Sample(string name)
{
Name = name;
}
public int Id { get; }
public string Name { get; }
}
and now that line causes error: 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.'
.
But if I'll add private set to Name
(or public) then everything works fine (even without empty constructor).
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
}
Can anyone explain me why this setter is required, for instance Id does not require that setter.