reggaeguitar
reggaeguitar

Reputation: 1804

Method that takes strongly typed property name as parameter

I'd like to refactor these two methods, the only difference is the property on the currentUser object that gets updated (and the parameter name, but that's not important).

public User SaveBaselineModelTemplateId(int baselineModelTemplateId)
{
    using (var db = _contextFactory.GetContext())
    {
        var currentUser = db.Users.Single(x => x.Login == Environment.UserName);
HERE -> currentUser.BaselineModelTemplateID = baselineModelTemplateId; 
        db.SaveChanges();
        return currentUser;
    }
}

public User SaveComparisonModelTemplateId(int comparisonModelTemplateId)
{
    using (var db = _contextFactory.GetContext())
    {
        var currentUser = db.Users.Single(x => x.Login == Environment.UserName);
HERE -> currentUser.ComparisonModelTemplateID = comparisonModelTemplateId; 
        db.SaveChanges();
        return currentUser;
    }
}

I'd like a method that I could call like SaveInt(ComparisonModelTemplateID, 42) or SaveInt(x => x.ComparisonModelTemplateID, 42). It seems like there is a way to do this using expression trees, but I couldn't find any exact examples of what I'm looking to do, thanks.

Upvotes: 1

Views: 80

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

You don't need an expression tree for this - a simple Action<User> would be sufficient:

private User ModifyAndSave(Action<User> modify) {
    using (var db = _contextFactory.GetContext())
    {
        var currentUser = db.Users.Single(x => x.Login == Environment.UserName);
        modify(currentUser);
        db.SaveChanges();
        return currentUser;
    }
}
public User SaveBaselineModelTemplateId(int baselineModelTemplateId)
{
     return ModifyAndSave(u => u.BaselineModelTemplateID = baselineModelTemplateId);
}
public User SaveComparisonModelTemplateId(int comparisonModelTemplateId)
{
     return ModifyAndSave(u => u.ComparisonModelTemplateID = comparisonModelTemplateId);
}

The two public methods above pass different action to the common ModifyAndSave method above. The common method takes an Action<User> which tells it what to do with the User object retrieved from the database before saving modifications.

Upvotes: 5

Related Questions