Kelly Robins
Kelly Robins

Reputation: 7313

Linq to SQL - Selecting a new object and performing an update

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.

Upvotes: 0

Views: 806

Answers (2)

ALT
ALT

Reputation: 1242

Here it is an simple example:

    using(DbContext dbContext = new DbContext())
    {
        UserData curData = dc.Users.Where(λ => (λ.Login == username) && λ.Active).SingleOrDefault(); // You need(!) to use SingleOrDefault or FirstOrDefault
        if(curData != null) 
        {
            curData.LastIP = 'xx.xx.xx.xx';
            curData.LastVisit = DateTime.Now;
            dbContext.SaveChanges();
        }
    }

Upvotes: 0

cdonner
cdonner

Reputation: 37668

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)

Upvotes: 1

Related Questions