Search code examples
exceptionlazy-loadingef-core-3.1proxies

EFCore 3 with UseLazyLoadingProxies enabled throws System.NotSupportedException: 'Parent does not have a default constructor


I am writting a DDD application and I am trying to use LazyLoading option.

The problem I am facing is that I can run my application OK if I don't use LazyLoading, but once I try to use UseLazyLoadingProxies(), when I get an entity I get the title exception. It seems that is thrown at Castle.DynamicProxies as I can see in the stacktrace

enter image description here

This is my entity:

public class Technology //: Entity
{
    // fields
    private readonly IList<SubTechnology> subTechnologies = new List<SubTechnology>();

    // properties

    public long Id { get; private set; }
    public virtual TechnologyName Name { get; private set; }
    public virtual IReadOnlyList<SubTechnology> SubTechnologies => subTechnologies.ToList().AsReadOnly();

    public Technology() { }

    public Technology(TechnologyName technologyName) : this()
    {
        Name = technologyName;
    }

    //public void AddSubtechnology(SubTechnology subTech)
    //{

    //}

and this is how I am calling my code:

public sealed class QuestionController
{
    private readonly InterviewsDbContext context;

    public QuestionController(InterviewsDbContext context)
    {
        this.context = context;
    }

    public string GetTechnology(long technologyId)
    {
        var tech = context.Technology.Single(t => t.Id == technologyId);
        return tech?.Name.Value;
    }
}

To me is indicating that I don't have my CTOR implemented, but I have tried public, protected, internal and I can't seem to make it work.

The only thing I can tell is that the Domain model do not live in the same assembly that my Context lives... not sure if has to do with the issue..

Any ideas? thx


Solution

  • Well I think I am really stupid, I just transformed my code into something really dumb (anemic model) and the problem went away.

    What I figured out was that the backing field being a IList<T> and the Property of type IReadOnlyList<T> and the proxy couln't create the type.

    The exception error was not much helpful in this case but changing IList<T> to List<T> fixed my issue.