简体   繁体   中英

Updating a record using LINQ Context?

i am trying to update a user table with a single value update, but i can't figure out what i'm doing wrong. this is what i have:

public static void ApplyROB(string  ROBread, string userName)
        {
            using (SERTEntities ctx = CommonSERT.GetSERTContext())
            {
                    // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
                    // Audit of the transfer
                datUser trUser = new datUserRole();
                trUser.ROB = ROBread;
                trUser.AccountName = userName;
                // Persist update to DB
                ctx.SaveChanges();

            }
        }

am i way off? nothing happens when i click on the update. how do i say, where username = username? did i do it right?

basically in need a simple:

update datUser set ROB = "Y" where AccountName= "myusername"

it's turning out to be a bit more complicated in LINQ using Context

please help.

You're not adding your new entity to the context, thus when you save, the context is unaware of any changes. You need something like...

ctx.datUserRoles.Add(datUserRole)

To do an update, you need to retreive an entity from the context, make changes to it, then save... so:

var entity=ctx.datUserRoles.SingleOrDefault(dur=>dur.AccountName==someUserName);
if(entity!=null)
{
    entity.someProp=someVal;
    ctx.SaveChanges();
}
else
{
    throw new UnexpectedOperationException(); //or however you want to fail
}

If you need an update. Maybe something like this:

public static void ApplyROB(string  ROBread, string userName)
{
    using (SERTEntities ctx = CommonSERT.GetSERTContext())
    {
        var trUser= ctx.datUserRole.Where(a=>a.AccountName==userName)
                                   .FirstOrDefault();
        if(trUser!=null)
        {
            trUser.ROB = ROBread;
            ctx.SaveChanges();
        }
    }
}

If you are sure that you will always have something to update you can use First() . Then you do not need to check if the trUser is null

spender is correct in a sense, incorrect in another: you want to update an existing record.

For that you'll need to select the record first, for instance:

var user = 
    (from u in ctx.datUserRoles 
    where u.AccountName == "accountname"
    select u).FirstOrDefault();

Where accountname is a valid thing of the same type - that doesn't matter, since you can select it how you want, you can touch that up to meet your criteria. Then once you have the item do the stuff:

if (user != null) {
    user.ROB = ROBread;
    ctx.SaveChanges();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM