views:

210

answers:

1

I have a query that selects data into a custom type-

UserData curData = dc.Users.Where(λ => (λ.Login == username) && λ.Active) 
    .Select( λ => new UserData { ID = λ.ID, UserName = λ.Login, isAdmin = λ.Admin, isTrusted = λ.Trusted, EMail = λ.E_mail ... });
     //Yeah I know this isn't a technically correct usage of 'λ' 
     //It is just a convenient variable name. Please don't hit me.

When I get a user's information I'd like to be able to update information like 'LastIP' and 'LastVisit' then submit the changes if the password is correct and the log in succeeds.

If I understand correctly the new object is detatched- so changes to it will not be saved if I alter it and call dc.SubmitChanges(). So what is the best way to perform an update in this situation. Do I need to just do another select and alter the data there, is there a way I can inline it on my initial statement?

Thanks for the help!


I put this together, figured I'd post it just in case anyone else needed an inline solution-

internal static class auth_extensions
{  

    public static IQueryable<User> Update(this IQueryable<User> data, Action<User> updateDelegate)
    {
        foreach (User cur in data)
        {
            updateDelegate(cur);
        }
        return data;

    }
}
    }

With the extension method in the assembly the query becomes-

UserData curData = dc.Users
    .Where(λ => (λ.Login == username) && λ.Active)
    .Update(λ => {
         λ.LastIP = HttpContext.Current.Request.UserHostAddress; 
         λ.lastVisit = DateTime.Now; 
    })
    .Select(loadDelegate).SingleOrDefault();

That being said cdonner's suggestion is excellent.

+1  A: 

Without more context, your intention is not clear. You are copying user attributes from a User object into a UserData object. Why don't you just edit a User object? Then SubmitChanges() will automatically persist your updates. i.e.

User curData = dc.Users.Where(λ => (λ.Login == username) && λ.Active)
cdonner
There is a lot of other data attached to the users object that I don't need or want at this point in the application. I also am going to be keeping the object in session state for quick retrieval so I'd like to keep them as stripped down as possible.
apocalypse9
Not a problem. When it is time to save, obtain the User from the database again, copy the data elements back from your UserData object, and call SubmitChanges().
cdonner