需要帮助使用LinQ更新记录。
我尝试更新记录,但它没有显示在数据库中。
主键在db和LinQ dbml文件中设置。
以下是代码:
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;
}
答案 0 :(得分:1)
当您添加新的记录用途InsertOnSubmit(Entity)
时,在您调用SubmitChanges()后,会自动更新您的对象上的任何自动编号(例如主要)。
更新实体时使用Attach(Entity)
。在附加实体后对其进行更改。在将其附加到Context之前进行更改将不会触发Update SQL,因为上下文会认为没有任何内容可以更新。
答案 1 :(得分:0)
您需要在insertonsubmit(obj);
submitchanges();