Search code examples
c#entity-frameworkservicestackormlite-servicestack

ServiceStack and entity framework Lazy Loading


I'm migrating our WCF web services to ServiceStack. Supose we have 3 entities. Let them be A, B and C.

  • A is father of B.
  • A is father of C.

In WCF we would have 3 methods to get A with his children:

public List<A> GetAWithBIncluded()
{
    return Repository.A.Include("B").ToList();
}

public List<A> GetAWithCIncluded()
{
    return Repository.A.Include("C").ToList();
}

public List<A> GetAWithBAndCIncluded()
{
    return Repository.A.Include("B").Include("C").ToList();
}

I'm having enormous difficult to translate this process to ServiceStack manner. Can you guys provide some examples?

The best I came up with is:

public class AResponse
{
    public List<A> As {get;set;}
    ....//One list of each type.
}

We know we cannot use WCF with lazyloading, but can ServiceStack and ormlite do the trick of fully automated process of data access without overcharging the application?


Solution

  • If you're using EF, I would probably do something like this:

    [Route("/a")]
    public class GetAs : IReturn<List<A>>
    {
        public bool IncludeB { get; set; }
        public bool IncludeC { get; set; }
    }
    
    public class AService : Service
    {
        private readonly AContext _aContext;
    
        public AService(AContext aContext)
        {
            _aContext = aContext;
        }
    
        public object Get(GetAs req)
        {
            var res = _aContext.As;
    
            if (req.IncludeB)
                res = res.Include("B");
    
            if (req.IncludeC)
                res = res.Include("C");
    
            return res.ToList();
        }
    }