简体   繁体   中英

Unable to update record in LINQ to SQL

Need help in updating records using LinQ.

I tried updating the record, but it does not display in the database.

The primary key is set in both db and LinQ dbml file.

Below are the codes:

RPHContrib _phContrib = new RPHContrib();
_phContrib.PHTableNo = phContrib.PHTableNo;
_phContrib.AmountFrom = phContrib.AmountFrom;
_phContrib.AmountTo = phContrib.AmountTo;
_phContrib.EmployeePH = phContrib.EmployeePH;
_phContrib.EmployerAmt = phContrib.EmployerAmt;
_phContrib.IsActive = phContrib.IsActive;
_phContrib.CreatedByNo = phContrib.CreatedByNo;
_phContrib.CreatedDate = phContrib.CreatedDate;
_phContrib.ModifiedByNo = SessionStateController.OnlineUserNo;
_phContrib.ModifiedDate = DateTime.Now;

LINQHelper.Instance.GenericDataContext<HRWizardDataContext>(GetDataContext(false));
LINQHelper.Instance.Update<RPHContrib>(_phContrib);

public bool Update<T>(T obj) where T : class, ICommon, new()
{
    using (var db = GetDBDataContext())
    {    
        db.Connection.Open();
        DbTransaction trans = db.Connection.BeginTransaction();
        db.Transaction = trans;

        // Populate object log                
        obj.IModifiedDate = DateTime.Now;

        try
        {
            Detach<T>(obj); // Detach LINQ entity from the original DataContext before attaching to the new one            
            db.GetTable<T>().Attach(obj, true);
            db.SubmitChanges();
            db.Transaction.Commit();
        }
        catch (Exception ex)
        {
            db.Transaction.Rollback();
            // TODO: Put error logging code here
            throw ex;
        }
        finally
        {
            if (db.Connection != null)
            {
                db.Connection.Close();
                db.Connection.Dispose();
            }
        }
    }
    return true;
}

When you are adding a new recored use InsertOnSubmit(Entity) , afterwhich any Auto Numbers (eg. primary) will be updated on your object automatically after you call SubmitChanges().

Use Attach(Entity) when you are updating an entity. Make changes to the entity after you have attached it. Making changes before you attach it to the Context will not trigger the Update SQL as the context will think there is nothing to update.

You need to do insertonsubmit(obj); before submitchanges();

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