How save my changes to database with Entity Framework? - c#

I was wondering if someone can help me in this case: I'm trying to save my changes to database, so I use a context, and I have _tblcustomer which is an object from my entity classes, here is my code:
private void BtnSaveCustomer_Click(object sender, EventArgs e)
{
if (CustomerMode == (int)CustomerModeOperaton.insert)
{
if (!string.IsNullOrWhiteSpace(TxtCustomerName.Text) ||
!string.IsNullOrWhiteSpace(TxtLastName.Text) ||
!string.IsNullOrWhiteSpace(TxtCustomerCode.Text))
{
tblCustomer Customer = new tblCustomer();
Customer.CustomerName = TxtCustomerName.Text.ToString();
Customer.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
if (!string.IsNullOrWhiteSpace(TxtCustomerAdress.Text))
{
Customer.CustomerAdresse = TxtCustomerAdress.Text.ToString();
}
else
{
Customer.CustomerAdresse = null;
}
if (!string.IsNullOrWhiteSpace(TxtCustomerPhone.Text))
{
Customer.CustomerPhone = Convert.ToInt32(TxtCustomerPhone.Text);
}
else
{
Customer.CustomerPhone = null;
}
if (!string.IsNullOrWhiteSpace(TxtCustomerCellphone.Text))
{
Customer.CustomerCellPhone = Convert.ToInt32(TxtCustomerCellphone.Text);
}
else
{
Customer.CustomerCellPhone = null;
}
Customer.CustomerLastName = TxtLastName.Text.ToString();
Customer.CustomerID = Guid.NewGuid();
Customer.rowguid = Guid.NewGuid();
using (var Context = new FactorEntities())
{
Context.tblCustomers.Add(Customer);
Context.SaveChanges();
}
MessageBox.Show("اطلاعات مشتری در سیستم ثبت شد");
// status=1;
}
else
{
MessageBox.Show("نام مشتری و نام خانوادگی و کد مشتری باید پر شوند");
}
}
else
{
using (var context = new FactorEntities())
{
var CustomerDetaile = context.tblCustomers.Find(CustomerID);
_tblCustomer = new tblCustomer();
_tblCustomer.CustomerID = CustomerDetaile.CustomerID;
_tblCustomer.CustomerName = TxtCustomerName.Text;
_tblCustomer.CustomerLastName = TxtLastName.Text;
_tblCustomer.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
_tblCustomer.CustomerAdresse = TxtCustomerAdress.Text;
context.SaveChanges();
}
MessageBox.Show("اطلاعات در سیستم ثبت شد");
}
}
Main part is here:
using (var context =new FactorEntities())
{
var CustomerDetaile = context.tblCustomers.Find(CustomerID);
_tblCustomer = new tblCustomer();
_tblCustomer.CustomerID = CustomerDetaile.CustomerID;
_tblCustomer.CustomerName = TxtCustomerName.Text;
_tblCustomer.CustomerLastName = TxtLastName.Text;
_tblCustomer.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
_tblCustomer.CustomerAdresse = TxtCustomerAdress.Text;
context.SaveChanges();
}
but I don't know why it does not save yet...
Thanks in advance.

I don't see anywhere you add the _tblCustomer object in the context, with something like in your "main part"
context.tblCustomers.Add(_tblCustomer);
If instead you want to modify an exiting object, you should write instead
CustomerDetaile.CustomerId = "the new id"
And now it will be saved.
What you are doing now, is creating a new customer, assigning its values and do nothing with it.

To save new object to database in this case you would need to use:
var obj = context.TableName.New();
obj.Name = "BLA";
obj.Salary = 32;
context.TableName.Add(obj);
context.SaveChanges();
To edit existing object in the table:
var obj = context.TableName.Find(id);
obj.Name = "BLA";
obj.Salary = 32;
context.Entry(obj).State = EntryState.Modified;
context.SaveChanges();
It always worked for me=) Apply this concept to your code and it may work.

I shouldn't make a new ... I have to write code for my select... I got it by #ChristianKouamé help here is my code:
using (var context =new FactorEntities())
{
var CustomerDetaile= context.tblCustomers.Find(CustomerID);
CustomerDetaile.CustomerID = CustomerID;
if (!string.IsNullOrWhiteSpace(TxtCustomerName.Text))
{
CustomerDetaile.CustomerName = TxtCustomerName.Text;
}
CustomerDetaile.CustomerLastName = TxtLastName.Text;
CustomerDetaile.CustomerAdresse = TxtCustomerAdress.Text;
CustomerDetaile.CustomerCellPhone = Convert.ToInt32(TxtCustomerCellphone.Text);
CustomerDetaile.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
context.SaveChanges();
}
thanks a lot.

Related

system missing method exception. why this happening

I was wondering if some one can help here. I have a project as a general which includes 5 layout. Now I'm trying to write api with dotnet core which use data access and commone Lay out of this general. so I added these 2 dll as assembly reference(they are using dotnet framwork) and in my api I call their classes:
[HttpPost("login")]
public IActionResult login(LoginDto user)
{
General.Common.cLoadUserPermission.stcLoginInfo _LI = new cLoadUserPermission.stcLoginInfo();
if (user.UserName.ToLower() == "adminy" && user.Password.ToLower()== "rddddlad91")
{
_LI.LoginError = enmLoginError.enmLoginError_NoError;
_LI.UserID = "d56d79f4-1f06-4462-9ed7-d4292322555d";
_LI.UserName = "مدير سيستم";
_LI.UserLoginName = "adminy";
_LI.PersonelID = Guid.Empty;
_LI.IsSupervisor = false;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
}
else
{
_LI.LoginError = enmLoginError.enmLoginError_UserNameNotFound;
}
//DateTime _t = General.Common.cPersianDate.GetDateTime("1364/02/03");
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
switch (_LI.LoginError)
{
case General.Common.enmLoginError.enmLoginError_NoError:
break;
case General.Common.enmLoginError.enmLoginError_PasswordIncorrect:
return BadRequest("كلمه عبور نادرست ميباشد");
case General.Common.enmLoginError.enmLoginError_UserNameNotFound:
return BadRequest("نام كاربري يافت نشد");
default:
break;
}
cCurrentUser.CurrentUserID = _LI.UserID;
cCurrentUser.CurrentPersonelID = _LI.PersonelID;
cCurrentUser.CurrentUserLoginName = _LI.UserLoginName;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
FiscalYearDS fiscalYearDs = null;
Guid selectedFiscalYearID = Guid.Empty;
using (IFiscalYear service = FacadeFactory.Instance.GetFiscalYearService())
{
fiscalYearDs = service.GetFiscalYearByOID(user.FiscalYear.ToString());
selectedFiscalYearID = fiscalYearDs.tblFiscalYear[0].FiscalYearID;
}
Configuration.Instance.CurrentFiscalYear = fiscalYearDs;
this.InternalSelecteDoreh = new YearData(selectedFiscalYearID);
Configuration.Instance.CurrentYear = this.SelectedDoreh;
General.Common.Data.FiscalYearDS generalfiscalyearDS = null;
using (General.Common.IFiscalYear service = General.Common.FacadeFactory.Instance.GetFiscalYearService())
{
generalfiscalyearDS = service.GetFiscalYearByOID(user.FiscalYear.ToString());
}
General.Common.Configuration.Instance.CurrentFiscalYear = generalfiscalyearDS;
General.Common.Configuration.Instance.CurrentYear = new General.Common.YearData(selectedFiscalYearID); ;
Sales.Common.YearData _SMSYearData = new Sales.Common.YearData(General.Common.Configuration.Instance.CurrentYear.FiscalYearID);
Sales.Common.Configuration.Instance.CurrentYear = _SMSYearData;
Sales.Common.Data.FiscalYearDS fiscalyearSMSDS = null;
selectedFiscalYearID = Guid.Empty;
using (Sales.Common.IFiscalYear service = Sales.Common.FacadeFactory.Instance.GetFiscalYearService())
{
fiscalyearSMSDS = service.GetFiscalYearByOID(General.Common.Configuration.Instance.CurrentYear.FiscalYearID.ToString());
//selectedFiscalYearID = fiscalyearDS.FiscalYear[0].FiscalYearID;
}
Sales.Common.Configuration.Instance.CurrentFiscalYear = fiscalyearSMSDS;
return Ok();
}
the main part is here :
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
This is my login method in general.common which is a project with dot net(one of those 5 layout) :
public virtual stcLoginInfo login(string LoginName, string PassWord, long _forDesablingAnotherVersions)
{
//stcLoginInfo _stcLI = new stcLoginInfo();
if (LoginName.ToLower() == "admin" && PassWord == "rdssolad91")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322555D","user"+"GUID");
_stcLI.UserLoginName = "adminy";
_stcLI.UserName = "مدير سيستم";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
return _stcLI;
}
if (LoginName.ToLower() == "admin" && PassWord == "dddddd")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322D14D","user"+"GUID");
_stcLI.UserLoginName = "admin";
_stcLI.UserName = "**مدير سيستم**";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
_stcLI.IsSupervisor = true;
return _stcLI;
}
UsersDS _ds = new UsersDS();
UsersDS.vwUsersDataTable tbl;
_stcLI.UserID = Guid.Empty.ToString();
using (IUsers service = FacadeFactory.Instance.GetUsersService())
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
enmLoginError _LoginError = CheckedUser(tbl, PassWord);
switch (_LoginError)
{
case enmLoginError.enmLoginError_NoError:
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String(tbl[0].UserID.ToString(), "user" + "GUID");
_stcLI.UserID = tbl[0].UserID.ToString();
_stcLI.PersonelID = tbl[0].PrincipalLegalEntityRef; //tbl[0].PersonelRef;
_stcLI.UserName = tbl[0].UserName;
break;
case enmLoginError.enmLoginError_PasswordIncorrect:
case enmLoginError.enmLoginError_UserNameNotFound:
case enmLoginError.enmLoginError_AccessDenied:
_stcLI.UserID = Guid.Empty.ToString();
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserName = "";//tbl[0].UserName;
break;
default:
break;
}
_stcLI.LoginError = _LoginError;
_stcLI.UserLoginName = LoginName;
_stcLI.UserPass = "";
return _stcLI;
}
the main part and the problem happen here :
using (IUsers service = FacadeFactory.Instance.GetUsersService()) // here I got error
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
in this line using (IUsers service = FacadeFactory.Instance.GetUsersService()) I get this error :
System.MissingMethodException: Method not found: 'System.Object System.Activator.GetObject(System.Type, System.String)'.
at General.Common.FacadeFactory.GetUsersService()
at General.Common.cLoadUserPermission.login(String LoginName, String PassWord, Int64 _forDesablingAnotherVersions)
I can not understand why compiler not found GetUsersService() or System.Object System.Activator.GetObject(System.Type, System.String) in that method. this facadfactory is a class in General.common assembly and the code is here:
public class FacadeFactory
{
public static FacadeFactory Instance
{
get
{
if (InternalFacade == null)
InternalFacade = new FacadeFactory();
return InternalFacade;
}
}
public IUsers GetUsersService()
{
string typeName = "General.Facade.UsersService";
IUsers temp = null;
if (Configuration.Instance.RemoteMode)
{
return new UsersClientProxy((IUsers)Activator.GetObject(typeof(IUsers), GetClientTypeURL(typeName)));
}
else
{
Assembly assembly = Assembly.LoadFrom(Configuration.Instance.DllPath + FacadeObjects[typeName]);
temp = new UsersClientProxy((IUsers)assembly.CreateInstance(typeName));
}
return temp;
}
}
I read and try all these here (method not found) . but non of them works, even clean and rebuild. thanks for reading this.
The method Activator.GetObject(Type, String) does not exist on .NET Core as you can see in the documentation for the Activator class. Refer to this comment for some more information.
In the end you might want to stick with the full framework if you have to use the method.

SaveChanges() doesn't insert any records to database

I'm using Entity Framework to add new records to the database, everything goes ok without any errors, but I don't see the new record in the database.
Update code works, but insert code doesn't work. No errors appear, but no records are inserted into the database.
My code :
var DBs2 = ConnectionTools.OpenConn();
DBs2.Configuration.AutoDetectChangesEnabled = false;
DBs2.Configuration.ValidateOnSaveEnabled = false;
var resList = CreatedSerials.Where(u => u.Item4 == VID).ToList();
foreach (var r in resList)
{
// if serial id ==0 => new then add it as new
if ( r.Item7 == 0)
{
try
{
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
ss.Add(purchasesItemSerials);
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
}
else
{
var DBs350 = ConnectionTools.OpenConn();
var UpdateSerial = DBs350.purchases_item_seriels.Find(r.Item7);
UpdateSerial.pitem_ID = pitem_ID;
UpdateSerial.stitems_ID = r.Item1;
UpdateSerial. pmain_ID = PurchasesID;
UpdateSerial.pitem_virtualID = r.Item4;
UpdateSerial.pis_CustomSerial = r.Item2;
UpdateSerial.pis_ExpireDate = r.Item3;
UpdateSerial.pis_Statues = r.Item6;
UpdateSerial.ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID"));
UpdateSerial.Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice"));
DBs350.SaveChanges();
}
}
try
{
DBs2.purchases_item_seriels.AddRange(ss);
DBs2.SaveChanges();
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
I also tried :
DBs2.Configuration.AutoDetectChangesEnabled = true;
DBs2.Configuration.ValidateOnSaveEnabled = true;
but again: no data is inserted, no errors appear
I also tried :
int returnCode = DBs2.SaveChanges();
and returnCode = 0
**I also tried : inserting just a single item then SaveChanges **
// if this serial is new
var NewSerialresList = CreatedSerials.Where(u => u.Item4 == VID && u.Item7 == 0).ToList();
if (NewSerialresList.Count() > 0)
{
var ss = new List<purchases_item_seriels>();
foreach (var r in NewSerialresList)
{
try
{
mrsalesdbEntities DBs002 = new mrsalesdbEntities();
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
//ss.Add(purchasesItemSerials);
DBs002.purchases_item_seriels.Add(purchasesItemSerials);
DBs002.SaveChanges();
}
catch (Exception ex)
{
Msg.Show("", ex.ToString(), 0);
}
}
int CC = ss.Count();
}
i use this function to change the connection variables at run-time :
public static mrsalesdbEntities OpenConn()
{
mrsalesdbEntities MrSalesContext = new mrsalesdbEntities();
MrSalesContext.ChangeDatabase
(
initialCatalog: myconn.database,
port: Convert.ToUInt32( myconn.port),
userId: myconn.uid,
password: myconn.password,
dataSource: myconn.server
);
return MrSalesContext;
}
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
uint port = 3307,
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "mrsalesdbEntities")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new MySqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.Database = initialCatalog;
if ((port) != 0)
sqlCnxStringBuilder.Port = port;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.Server = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
//sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}

Modified entity is not applied into the database

I am trying to update loan balance based on the payment made by a member.
Payment goes well and it is inserted as expected but during the update of the table LOANBAl, nothing is modified, bellow is my code:
public void UpdateLoanBal(MPAreceipting mpa, string id)
{
using (BOSAEntities db = new BOSAEntities())
{
General gn = new General();
gn.GetUser();
gn.GetServerDate();
LoanRepayment lr = new LoanRepayment();
lr.GetMemberDeduction(loanno);
var lOANBAL = db.LOANBALs.Find(id);
var lb = new LOANBAL();
lb.AuditID = gn.sysUser;
lb.AuditTime = gn.serverDate;
lb.Balance = Convert.ToDecimal(lr.loanBalance);
lb.IntrOwed = Convert.ToDecimal(lr.intOwed);
lb.LastDate = mpa.dateDeposited;
db.Entry(lOANBAL).State = EntityState.Modified;
db.SaveChanges();
}
}
I used the lOANBAL which is an entity and update its properties.
public void UpdateLoanBal(MPAreceipting mpa, string id)
{
var db = new BOSAEntities();
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
var lOANBAL = db.LOANBALs.Find(loanno);
General gn = new General();
gn.GetUser();
gn.GetServerDate();
LoanRepayment lr = new LoanRepayment();
lr.GetMemberDeduction(loanno);
lOANBAL.LoanNo = loanno;
lOANBAL.AuditID = gn.sysUser;
lOANBAL.AuditTime = gn.serverDate;
lOANBAL.Balance = Convert.ToDecimal(lr.loanBalance);
lOANBAL.IntrOwed = Convert.ToDecimal(lr.intOwed);
lOANBAL.LastDate = mpa.dateDeposited;
lOANBAL.TransactionNo=lr.
db.Entry(lOANBAL).State = EntityState.Modified;
db.SaveChanges();
dbContextTransaction.Commit();
}
catch (DbEntityValidationException Exc)
{
dbContextTransaction.Rollback();
string errormessage = string.Join(";",
Exc.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
throw new DbEntityValidationException(errormessage);
}
}
}

Entity saves ok but will not update record no matter what I do

Context is not saving to the database no matter what i do it will insert a new record fine but not save. This is using sql server and the user had permissions ot update data have already checked this
private void btnOk_Click(object sender, EventArgs e)
{
SourceContext SourceDal = new SourceContext();
Appointment _appointment = new Appointment();
int errorCount = 0;
Patient _patient = new Patient();
_patient = SourceDal.getPatientByPatientId(txtPatientId.Text);
_patient.SSN = txtSSN.Text;
_patient.FirstName = txtPatientFirstName.Text;
_patient.LastName = txtPatientLastName.Text;
_patient.Middle = txtPatientMiddle.Text;
_patient.AddressOne = txtPatientAddressOne.Text;
_patient.City = txtPatientCity.Text;
_patient.State = txtPatientState.Text;
_patient.ZipCode = txtPatientZip.Text;
_patient.HomePhone = txtPatientHomePhone.Text;
_patient.WorkPhone = txtPatientWorkPhone.Text;
_patient.CellPhone = txtPatientCellPhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnWorkPhone.Checked == true)
_patient.ApptPhone = txtPatientWorkPhone.Text;
_patient.BirthDate = dtBirthDate.DateTime;
_patient.emailAddress = txtPatientEmail.Text;
_patient.Race = (int)dpRace.SelectedValue;
_patient.Ethnicity = (int)dpEthnicity.SelectedValue;
_patient.Language = (int)dpLanguages.SelectedValue;
_patient.AlertNote = txtPatientNotes.Text;
if (dpGender.Text == "")
{
dpGender.Focus();
errorCount = 1;
lblGenderRequired.Text = "* Gender is required.";
}
else
{
errorCount = 0;
lblGenderRequired.Visible = false;
}
_patient.Gender = dpGender.Text.Substring(0, 1);
_patient.PatientID = txtPatientId.Text;
txtPatientFirstName.Text = _patient.FirstName;
txtPatientLastName.Text = _patient.LastName;
// IF ITS SAVE NEW GO AHEAD ADD IT TO THE CONTEXT.
SourceDal.AddToPatient(_patient);
}
Add to paitent has the following
public void AddToPatient(Patient newPatient)
{
using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
{
myContext.Patients.Add(newPatient);
if (newPatient.ID == 0)
{
myContext.Entry(newPatient).State = EntityState.Added;
}
else
{
myContext.Entry(newPatient).State = EntityState.Modified;
}
try
{
myContext.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
}
It adds in the record fine but it just wont save the current record no matter what i do even though all the details are correct. But when i reload the form and the application the update is not there the email address is not saved no are any the other updates.
I suspect I'm not familiar with that entity framework, as I'm unfamiliar with the some of that syntax, but you should be able to use something like this:
public void AddToPatient(Patient newPatient)
{
SMBASchedulerEntities dbContext = new SMBASchedulerEntities();
if (newPatient.ID.ToString() != "0")
{//Update the record
Patient updatePatient = dbContext.Patients.Single(p => p.ID == newPatient.ID);
updatePatient.FirstName = newPatient.FirstName;
updatePatient.LastName = newPatient.LastName;
...
...
dbContext.SubmitChanges();
}
else
{//Insert a new record
Patient insertPatient = new Patient();
insertPatient.FirstName = newPatient.FirstName;
insertPatient.LastName = newPatient.LastName;
...
...
dbContext.Patients.InsertOnSubmit(insertPatient);
dbContext.SubmitChanges();
}
}
To put this another way, check to see if you need to insert or update a new patient first, before inserting it every time.

how to get history info from QC using OTA

Below My Code that gets info of Bug history from QC. I have problem with
AuditPropertyFactoryFilter which does not filter. AuditPropertyFactory has more than thousand rows.
If I comment
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text); and uncomment
next line, auditPropertyFactory has several rows only but it isn't filtered as i need.
Can anyone get some advice?
public List<QCBugHistory> retrieveHistoryFromBug(string bugId)
{
List<QCBugHistory> history = new List<QCBugHistory>();
try
{
TDConnection qcConnection = new TDConnection();
qcConnection.InitConnectionEx(qcUrl);
qcConnection.ConnectProjectEx(qcDomain, qcProject, qcLogin);
if (qcConnection.Connected)
{
AuditRecordFactory auditFactory = qcConnection.AuditRecordFactory as AuditRecordFactory;
TDFilter historyFilter = auditFactory.Filter;
historyFilter["AU_ENTITY_TYPE"] = "BUG";
historyFilter["AU_ENTITY_ID"] = bugId;
historyFilter["AU_ACTION"] = "Update";
historyFilter.Order["AU_TIME"] = 1;
historyFilter.OrderDirection["AU_TIME"] = 1;
var auditRecordList = auditFactory.NewList(historyFilter.Text);
log.Info("кол-во в истории " + auditRecordList.Count);
if (auditRecordList.Count > 0)
{
foreach (AuditRecord audit in auditRecordList)
{
QCBugHistory bugHistory = new QCBugHistory();
bugHistory.actionType = audit["AU_ACTION"];
bugHistory.changeDate = audit["AU_TIME"];
AuditPropertyFactory auditPropertyFactory = audit.AuditPropertyFactory;
var changesHistoryFilter = auditPropertyFactory.Filter;
changesHistoryFilter["AP_PROPERTY_NAME"] = "Status";
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text);
//var changesList = auditPropertyFactory.NewList("");
if (changesList.Count > 0)
{
foreach (AuditProperty prop in changesList)
{
//prop.EntityID
if (prop["AP_PROPERTY_NAME"] == "Status")
{
bugHistory.oldValue = prop["AP_OLD_VALUE"];
bugHistory.newValue = prop["AP_NEW_VALUE"];
history.Add(bugHistory);
}
}
}
}
}
}
}
catch (Exception e)
{
log.Error("Проблема соединения и получения данных из QC ", e);
}
return history;
}
Try this (in C#):
1) Having only BUG ID param (BUGID below):
BugFactory bgFact = TDCONNECTION.BugFactory;
TDFilter bgFilt = bgFact.Filter;
bgFilt["BG_BUG_ID"] = BUGID; // This is a STRING
List bugs = bgFilt.NewList();
Bug bug = bugs[1]; // is 1-based
bug.History;
2) Having the Bug object itself, just do:
bug.History;

Categories

Resources