How to change the Entity State from Modified to Added using EF 3.5

Jan 23, 2012 at 10:57 AM
Edited Jan 23, 2012 at 11:07 AM

How to change the the EntityState from Unchanged/Modified to Added in Entity frame work 3.5. Not using EF 4.
 


Here is my code 
 

 

 

 IQueryable<AGMT_DELR> agmtDelr;

 

REFI.DAL.

 

AgmtDealerDAL da = new AgmtDealerDAL();

REFI.DAL.EntityFW.

AGMT_DELR agmtDlr;

 

REFI.DAL.EntityFW.

AGMT_DELR_HIST delrHistory = new AGMT_DELR_HIST();

 

 

string delrHistoryValue = "TRUE";

 

try 

 

{

 

 

agmtDelr = (from item incontext.AGMT_DELRS

 

where item.AGMT.AGMT_ID_REFI == agmtId 

  select item);

 foreach (var item in agmtDelr)

 

{ 

 

if (item.DELR_CONTR_EXPI_DT > expirationDate)

 

{

agmtDlr = GetAgmtDealer(item.AGMT_DELR_ID);

 

 

if (agmtDlr != null)

 

{

delrHistory.DELR_ID = agmtDlr.DELR.DELR_ID;

delrHistory.AGMT_DELR_ID = agmtDlr.AGMT_DELR_ID;

delrHistory.CONTR_TYP = agmtDlr.CONTR_TYP;

delrHistory.DELR_CONTR_EFF_DT = agmtDlr.DELR_CONTR_EFF_DT;

delrHistory.DELR_CONTR_EXPI_DT = agmtDlr.DELR_CONTR_EXPI_DT;

delrHistory.IS_CUR = agmtDlr.IS_CUR;

delrHistory.AGMT = agmtDlr.AGMT;

delrHistory.MOD_BY = userId;

delrHistory.MOD_DT = System.

 

DateTime.Now;

 

delrHistory.CRTE_BY = userId;

delrHistory.CRTE_DT = System.

 

DateTime.Now;

 

  ObjectStateEntry objEn;

 

 

DbEntity.ObjectStateManager.TryGetObjectStateEntry(delrHistory,outobjEn);

 

if (objEn.State == System.Data.EntityState.Modified)

 

 

{

 

 //I'm not able to uncomment the above line as it saying read only property. But I need the Entity state should be added to add a new item.
//objEn.State = System.Data.EntityState.Added;
 

 

 

 DbEntity.Detach(delrHistory);

 

 

 

DbEntity.CreateEntityKey(

"AGMT_DELR_HISTS", delrHistory);

 

DbEntity.Attach(delrHistory);

 

 

DbEntity.SaveChanges();

 

 

//DbEntity.Detach(delrhistory); 

 

 

//context.ChangeObjectState(entity, System.Data.EntityState.Added);

 

 

}

 

 

if (delrHistoryValue.ToUpper() == "TRUE")

 

{

item.DELR_CONTR_EXPI_DT = expirationDate;

item.IS_CUR =

 

true;

 

item.MOD_BY = userId;

item.MOD_DT = System.

 

DateTime.Now;

 

}

}

}

 

 

 

if (agmtDelr != null)

 

 

return UpdateDealers();

 

 

else

 

 

 

return null;

 

}

 

 

catch (Exception e)

 

{

 

 

return null;

 

}

 

 

 

finally 

 

{

agmtDelr =

 

null;

 

}

 

 

}

delrHistoryValue = AddDealerHistory(delrHistory);

 


Please help me

 

Thanks
Ravi