Mark Hollas Mark Hollas - 27 days ago 14
C# Question

C# Action Delegates and EF Repository Scope Issues

I have a Wrapper method on a WebApi Controller that exposes and Action Delegate. I use it to talk to the service layer. The Action passes a UnitOfWork that has my EF Repositories for the models

The problem is when I try populate a model passed from the controller to service, the changes, while they apply at the service layer, do not reflect on the Controller. However the commented out approach does work and I do not understand why

//In controller
Unit(uw => officeService.Get3(uw, user, User.Identity.GetUserId().ToString()));
return Ok(user);
//the returned user does not have changes applied

//Service
public void Get3(UnitOfWork uw, Member model, string id, string include = null)
{
object m = uw.MemberRepository.Get(u => u.UserId == id).FirstOrDefault();
model = (Member)m;
//model.Created = m.Created;
//model.ExpiryInDays = m.ExpiryInDays;
// and so on...
}

Answer

The reference to model is passed by value, so changing assigning to model in Get3 won't have any effect on the caller. You can either pass by ref:

public void Get3(UnitOfWork uw, ref Member model, string id, string include = null)

Or return it (as you seem to be ignoring the parameter anyway).

public Member Get3(UnitOfWork uw, string id, string include = null)
{
    // ...
    return model;
}

This would require an overload of Unit that accepts a Func and returns the result.

Comments