Musikero31
Musikero31

Reputation: 3153

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;
}

Upvotes: 1

Views: 1029

Answers (2)

Antarr Byrd
Antarr Byrd

Reputation: 26169

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

Upvotes: 0

Andy Clark
Andy Clark

Reputation: 3523

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.

Upvotes: 1

Related Questions