I'm making a rather "simple" piece of software and at the moment I'm working with one table in my database and reading from the database works and now I was trying to implement inserting into the database, which seems to work as long as the program is running, but when I stop the program (stop debugging in VS) and launch it again, the rows don't seem to be in the database (already checked the .mdf database itself for the rows but they can't be found).
This is the piece of code:
public void saveKlant(klant nieuweKlant)
{
KlantGegevens newKlant = new KlantGegevens();
newKlant.klantNaam = nieuweKlant.naam;
newKlant.klantStraat = nieuweKlant.straat;
newKlant.klantPostcode = nieuweKlant.postcode;
newKlant.klantHuisNummer = nieuweKlant.huisnummer;
newKlant.klantGSM = nieuweKlant.gsm;
newKlant.klantTel = nieuweKlant.telnummer;
newKlant.klantGebDatum = nieuweKlant.gebDatum;
newKlant.klantEmail = nieuweKlant.email;
using (kapsalonEntities context = new kapsalonEntities())
{
try
{
context.KlantGegevens.AddObject(newKlant);
int test = context.SaveChanges();
}
catch
{
throw new InvalidOperationException("het object kon niet toegevoegd worden");
}
}
}
"test" equals 1 (so context.SaveCHanges() = 1) when running the program.
what would be the reason for the data to not be added persistently? since I do use a Context.SaveChanges()?
Thanks in advance.
It looks like you didn't check of the property where the database each time copies himself toi the debug directory. That's why you always get your default data again. Set the property to "if newer"
Related
I am trying to execute below query
using (var dbcontext = new EVEntities())
{
var data_header = dbcontext.Cl.Where(x => x.PKey ==
header_key).FirstOrDefault();
if (data_header != null)
{
data_header.EstimatedCost = Math.Round(estimated_cost,2);
data_header.ClaimedCost = Math.Round(claimed_cost,2);
dbcontext.Entry<Cl>(data_header).State = System.Data.Entity.EntityState.Modified;
dbcontext.SaveChanges();
Writelog("Updated");
}
}
Here Writelog write in a text file and it is working always. But the field in Cl is not getting updated. In between the data is getting updated also.
Connection String
<connectionStrings><add name="EVEntities" connectionString="metadata=res://*/xxx_Entity_Model.csdl|res://*/xxx_Entity_Model.ssdl|res://*/xxx_Entity_Model.msl; provider=System.Data.SqlClient;provider connection string="data source=xxxxxx;initial catalog=xxxxx;persist security info=True;user id=xx;password=xxxxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/></connectionStrings>
Edit1
tried raw update also
dbcontext.Database.ExecuteSqlCommand(#"UPDATE dbo.Claims
SET EstimatedCost = #e_cost, ClaimedCost = #c_cost WHERE Pkey =
#p_key",
new SqlParameter("e_cost", Math.Round(estimated_cost, 2)),
new SqlParameter("c_cost", Math.Round(claimed_cost, 2)),
new SqlParameter("p_key", claim_header_key));
same outcome. It get updated in between. No error.
You didn't give us enough information to give you the solution. Therefore I give you a method to debug the problem.
Does the DbContext think that anything must be saved?
What SQL is sent to the database?
When you call SaveChanges, DbContext checks its ChangeTracker to see if anything must be updated. Consider to write some Debug code to detect whether there are changes.
Insert just before SaveChanges:
bool changesDetected = dbContext.ChangeTracker.HasChanges;
It might be that you need to call DetectChanges() first. I'm not sure.
If there are Changes, check if the item that you think that should be updated is changed:
IEnumerable <DbEntityEntry<Cl>> entries = dbContext.ChangeTracker.Entries<Cl>;
// We're expecting exactly one entry:
DbEntityEntry<Cl> myEntry = entries.SingleOrDefault();
Assert(myEntry != null);
If null, try to find out why it is not tracked. Was it tracked after you fetched it, before you changed it? Do you have somewhere tracking switched off? Write some other debug code where you fetch some other data. Is that tracked?
If not null, then apparently your Cl is tracked. It ought to be changed:
Assert(myEntry.State == EntityState.Modified);
If not modified, fetch the original values and the current values:
DbPropertyValues originalValues = myEntry.OriginalValues;
DbPropertyValues currentValues = myEntry.currentValues;
In your debugger, check them, or write some debug code to compare the original value with the current values. Are the changed values correct?
I'm not sure if entity framework will try to update objects that are unmodified and of which the original values are not equal to the current values. We'll find out to see what SQL is created when you do the SaveChanges.
It would be nice if your database can log all communications.
You can also log what entity framework sends to your database. For this, use property DbContext.Database.Log. For example:
dbContext.Database.Log = Console.Write;
dbContext.SaveChanges();
If you can't write to Console, write a method:
private List<string> SqlCommands {get;} = new List<string>();
void LogSqlCommands(string sqlCommand)
{
this.SqlCommands.Add(sqlCommand);
}
And in your method that following debug code:
using (var dbcontext = new EVEntities())
{
this.SqlCommands.Clear();
dbContext.Database.Log = this.LogSqlCommands;
var data_header = ... etc
dbContext.SaveChanges();
}
Put a breakpoint after SaveChanges and check the generated SQL.
Hope these debugging tips help you to find the cause of your problem
I have a method that queries a table for the count of its records. QA has discovered an "edge case" where if a particular operation is canceled in a particular order and speed (as fast as possible), the GUI "forgets" about the rest of the records in that table (the contents of the tables are uploaded to a server; when each one finishes, the corresponding table is deleted).
To be clear, this table that is having records deleted from it and then queried for count ("workTables") is a table of table names, that are deleted after they are processed.
What I have determined (I'm pretty sure) is that this anomaly occurs when a record from the "workTables" table is in the process of being deleted when the workTables table is queried for the count of its records. This causes an exception, which causes the method to return -1, which in our case indicates we should cuase the GUI to not display those records.
Is there a way to check if a table is in the process of having a record deleted from it, and wait until after that operation has completed, before proceeding with the query, so that it won't throw an exception?
For those interested in the specifics, this method is the one that, under those peculiar circumstances, throws an exception:
public int isValidTable(string tableName)
{
int validTable = -1;
string tblQuery = "SELECT COUNT(*) FROM ";
tblQuery += tableName;
openConnectionIfPossibleAndNecessary();
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
object objcnt = cmd.ExecuteScalar();
validTable = Int32.Parse(objcnt.ToString());
}
catch (Exception ex)
{
validTable = -1;
}
return validTable;
}
...and this is the method that deletes a record from the "workTables" table after the corresponding table has had its contents uploaded:
private void DropTablesAndDeleteFromTables(string recordType, string fileName)
{
try
{
WorkFiles wrkFile = new WorkFiles();
int tableOK = 0;
DataSet workfiles;
tableOK = wrkFile.isValidWorkTable(); // -1 == "has no records"
if (tableOK > 0) //Table has at least one record
{
workfiles = wrkFile.getAllRecords();
//Go thru dataset and find filename to clean up after
foreach (DataRow row in workfiles.Tables[0].Rows)
{
. . .
dynSQL = string.Format("DELETE FROM workTables WHERE filetype = '{0}' and Name = '{1}'", tmpType, tmpStr);
dbconn = DBConnection.GetInstance();
dbconn.DBCommand(dynSQL, false);
populateListBoxWithWorkTableData();
return;
} // foreach (DataRow row in workfiles.Tables[0].Rows)
}
}
catch (Exception ex)
{
SSCS.ExceptionHandler(ex, "frmCentral.DropTablesAndDeleteFromTables");
}
}
// method called by DropTablesAndDeleteFromTables() above
public int isValidWorkTable() //reverted to old way to accommodate old version of DBConnection
{
// Pass the buck
return dbconn.isValidTable("workTables");
}
I know this code is very funky and klunky and kludgy; refactoring it to make more sense and be more easily understood is a long and ongoing process.
UPDATE
I'm not able to test this code:
lock (this)
{
// drop the table
}
...yet, because the handheld is no longer allowing me to copy files to it (I get, "Cannot copy [filename.[dll,exe] The device has either stopped responding or has been disconnected" (it is connected, as shown by ActiveStync))
If that doesn't work, I might have to try this:
// global var
bool InDropTablesMethod;
// before querying that database from elsewhere:
while (InDropTablesMethod)
{
Pause(500);
}
UPDATE 2
I've finally been able to test my lock code (copies of binaries were present in memory, not allowing me to overwrite them; the StartUp folder had a *.lnk to the .exe, so every time I started the handheld, it tried to run the buggy versions of the .exe), but it doesn't work - I still get the same conflict/contention.
UPDATE 3
What seems to work, as kludgy as it may be, is:
public class CCRUtils
{
public static bool InDropTablesMethod;
. . .
if (CCRUtils.InDropTablesMethod) return;
CCRUtils.InDropTablesMethod = true;
. . . // do it all; can you believe somebody from El Cerrito has never heard of CCR?
CCRUtils.InDropTableMethod = false;
UPDATE 4
Wrote too soon - the bug is back. I added this MessageBox.Show(), and do indeed see the text "proof of code re-entrancy" at run-time.
while (HHSUtils.InDropTablesMethod)
{
MessageBox.Show("proof of code re-entrancy");
i++;
if (i > 1000000) return;
}
try
{
HHSUtils.InDropTablesMethod = true;
. . .
}
HHSUtils.InDropTablesMethod = false;
...so my guess that code re-entrancy may be a problem is correct...
I have developed a WCF api which is using nHibernate. I am new to this. I have used session.update to take care of transaction. I have a for loop in which based on select condition I am updating a record ie. If A is present in tabel1 then I am updating the table else inserting a new entry.
I am getting "could not execute query." when trying to execute a select query on a table which was previously being updated by adding a new entry in the table.
What I think is, because I am using session.save(table1) and then trying select entries from that table I am getting an error. Since session.save temporarily locks the table I am not able to execute a select query on that table.
What can be the solution on this?
Update:
This the for loop I am using to check in the database for some field:
using (ITransaction tranx = session.BeginTransaction())
{
savefunction();
tranx.Commit();
}
Save function:
public void savefunction()
{
for (int i = 0; i < dictionary.Count; i++)
{
ICandidateAttachmentManager candidateAttach = new ManagerFactory().GetCandidateAttachmentManager();
CandidateAttachment attach = new CandidateAttachment();
attach = checkCV();
if(attach == null)
{
//insert new entry into table attach
session.save(attach);
}
}
}
checkCV function:
public void checkCV()
{
using (ICandidateAttachmentManager CandidateAttachmentManager = new ManagerFactory().GetCandidateAttachmentManager())
{
IList<CandidateAttachment> lstCandidateAttachment = CandidateAttachmentManager.GetByfkCandidateId(CandidateId);
if (lstCandidateAttachment.Count > 0)
{
CandidateAttachment attach = lstCandidateAttachment.Where(x => x.CandidateAttachementType.Id.Equals(FileType)).FirstOrDefault();
if (attach != null)
{
return null;
}
else
{
return "some string";
}
}
}
}
What happening here is in the for loop if say for i=2 the attach value comes to null that I am entering new entry into attach table. Then for i=3 when it enters checkCV function I get an error at this line:
IList lstCandidateAttachment =
CandidateAttachmentManager.GetByfkCandidateId(CandidateId);
I think it is because since I am using session.save and then trying to read the tabel contents I am unable to execute the query and table is locked till I commit my session. Between the beginTransaction and commit, the table associated with the object is locked. How can I achieve this? Any Ideas?
Update:
I read up on some of the post. It looks like I need to set isolation level for the transaction. But even after adding it doesn't seem to work. Here is how I tried to inplement it:
using (ITransaction tranx = session.BeginTransaction(IsolationLevel.ReadUncommitted))
{
saveDocument();
}
something I don't understand in your code is where you get your nHibernate session.
Indeed you use
new ManagerFactory().GetCandidateAttachmentManager();
and
using (ICandidateAttachmentManager CandidateAttachmentManager = new ManagerFactory().GetCandidateAttachmentManager())
so your ManagerFactory class provides you the ISession ?
then you do:
CandidateAttachment attach = new CandidateAttachment();
attach = checkCV();
but
checkCV() returns either a null or a string ?
Finally you should never do
Save()
but instead
SaveOrUpdate()
Hope that helps you resolving your issue.
Feel free to give more details
I'm using an Oracle 11g database with the ADO.NET Entity Data Model. Every now and then I run into this error and I have no idea what's causing it. I'm assuming it's something in the EDMX file or the designer file for it but I can't seem to figure it out. I've deleted the model, added it, updated, etc multiple times and can't figure out the issue. It works on other pages but this one seems to be a problem.
This has happened before, but simply removing and re-adding the table worked. Any ideas on how to fix this?
using (ODSData.Entities entities = new Entities())
{
var info = from item in entities.ODS_VALIDATIONRULE
select item;
newPK = Convert.ToInt32(info.Max(p => p.VALIDATIONRULEID)) + 1;
try
{
ODS_VALIDATIONRULE newRule = new ODS_VALIDATIONRULE();
newRule.ALLOWNULLIND = isNull;
newRule.CREATEDATE = DateTime.Now;
newRule.FAILIND = isFail;
newRule.MAXVALUEFACTOR = max;
newRule.MINVALUEFACTOR = min;
newRule.RULEDESCRIPTION = description;
newRule.SOURCESYSTEM = source;
newRule.TABLENAME = table;
newRule.COLUMNNAME = column;
newRule.DATATYPE = datatype;
newRule.VALIDVALUELIST = valid;
newRule.VALIDATIONRULEID = newPK;
entities.AddToODS_VALIDATIONRULE(newRule);
entities.SaveChanges();
insertAccepted = true;
}
catch
{
// Log Error
}
The error I'm getting is this: "An error occurred while preparing the command definition. See the inner exception for details."
Inner Exception: "Operation is not valid due to the current state of the object."
Apparently the issue here was somewhere in the EDMX file and the way it read from Oracle. I deleted the table and recreated it in the DB as well as the EDMX and then added it back. It worked fine then.
The only thing I see that seems odd is you aren't using a sequence for your Pk value. You may try creating one and see if that helps at all.
I'm trying to save two Lists of objects in the phone ApplicationSettings, but I'm stuck at a strange issue (But it's probably me making a silly mistake somewhere).
If I only save one of the lists, it works as supposed - It'll save it, and reload it when app is launched next time.
But if I try to save 2 lists, none of them seem to be saved correctly. No errors or anything, just "blankness".
See code below.
//My save method
public void Gem()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains(INDTASTNINGER_LIST))
{
settings[INDTASTNINGER_LIST] = _indtastningsListe;
}
else
settings.Add(INDTASTNINGER_LIST, _indtastningsListe);
if (settings.Contains(INDTASTNINGER_LIST2))
{
settings[INDTASTNINGER_LIST2] = _indtastningsListe2;
}
else
settings.Add(INDTASTNINGER_LIST2, _indtastningsListe2);
settings.Save();
}
//Constructor supposed to load settings
public Indtastninger()
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains(INDTASTNINGER_LIST))
{
_indtastningsListe = null;
_indtastningsListe = (List<Indtastning>)settings[INDTASTNINGER_LIST];
}
if (settings.Contains(INDTASTNINGER_LIST2))
{
_indtastningsListe2 = null;
_indtastningsListe2 = (List<Indtastning>)settings[INDTASTNINGER_LIST2];
}
}
What am I doing wrong?
If I comment out the part with "list2" stuff, the first one will be saved/retrieved perfectly.
I have faced the same issue some time ago, the problem is that you only can save on the IsolatedStorage objects that are XML serializables.
if you save other object, it will work even with the debugger but when the app is restarted, all the saved data is lost.