context.SaveChanges does not save changes without any error - c#

I'm trying to add one object to database table using this code, in my console application:
using (var context = new Database1Entities())
{
var number = new Numbers()
{
Num=15
};
context.Numbers.AddObject(number);
context.SaveChanges();
Console.WriteLine(number.Id);
Console.ReadLine();
}
My model:
Connection string:
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
packages.config:
<packages>
<package id="EntityFramework" version="6.1.0" targetFramework="net40-Client" />
</packages>
but it does not add any thing to database and whenever it runs, it returns 1 as Id of stored Number.

As Abhay Prince said: There is no any syntactical or logical error or mistake in this code.
Problem: I should say that always changes which program do on mdf file was on file that automatically copied to bin/debug folder; so when I check my mdf file that is reachable in Visual Studio, it does not have any changes affected by application.

There is no any syntactical or logical error or mistake in your code. It should work perfectly, if it is not giving desired output, try clean your project or restart your Visual Studio may be it is due to cache or log data.
Try restart your Visual Studio and let we know if it works correct or not..

Try
context.Numbers.AddObject(number);
context.Entry(number).State = EntityState.Added;
context.SaveChanges();

If I understand this correct
What is difference between dbcontext.Add and dbcontext.AddObject
then you need to set manually that the context has been changed before it can save to database.
If you instead use
context.Numbers.Add(number);
The context should automatically set that the context has changed and the savechanges should work.

put SaveChanges() in try catch
it captures the SaveChanges() error.

Related

AccessViolationException in .NET Core 5 with Advantage Data Provider

I need to connect to Advantage Database for a Worker I'm working on.
I'm using the NuGet package Advantage.Data.Provider like so:
var conn = new AdsConnection("Data Source=\\Users\\[mypath];Initial Catalog=Test.add; User ID=adssys; Password=passw; ServerType=LOCAL");
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
return conn;
After adding lots of .dll in System32 to fix other errors, I'm now stuck in this one:
Exception has occurred: CLR/System.AccessViolationException Ocorreu
uma exceção sem tratamento do tipo "System.AccessViolationException"
em Advantage.Data.Provider.dll: 'Attempted to read or write protected
memory. This is often an indication that other memory is corrupt.'
I can't get it to work. I've tried using others NuGets like AdoNetCore.AseClient and iAnywhere.Data.SQLAnywhere, but they also cause errors.
If anyone could help me with this error or has a better solution to my problem, I would appreciate it.
I'm using VS Code and C#.
What ended up working for me was:
First just like #Pieterjan said-
Use the NuGet package Advantage.Data.Provider (Version 8.10.1.2)
Install the .NET Data Provider corresponding to my DB version (https://devzone.advantagedatabase.com/dz/content.aspx?Key=20&Release=16&Product=4&Platform=11)
Then-
Get ace32.dll, adsloc32.dll, axcws32.dll and adslocal.cfg from C:\Program Files (x86)\Advantage 10.10\ARC and put it in an environment path location (like System32, but it would be recommended to create a new one just for this)
Run the project with dotnet run -r win-x86
Apparently the NuGet package can only be run with x86, I think that was the main problem
Install the Advantage Database Server dataprovider (ADS 8.1 provider)
Use the following code to create a database connection:
var connection = System.Data.Common.DbProviderFactories.GetFactory("Advantage.Data.Provider").CreateConnection();
connection.ConnectionString = "DATA SOURCE=C:\Ads\Databases\Example.add;ServerType=remote;USER ID=ADSSYS;PASSWORD=xxx;";
connection.Open();
var command = connection.CreateCommand();
command.CommandTask = "";
foreach (var param in Parameters) {
var par = command.CreateParameter();
par.ParameterName = "";
par.Value = "";
// par.DbType = System.Data.DbType.Boolean
command.Parameters.Add(par);
}
Modify your app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
<system.data>
<DbProviderFactories>
<clear />
<add name="Advantage Data Provider" invariant="Advantage.Data.Provider" description="" type="Advantage.Data.Provider.AdsFactory, Advantage.Data.Provider, Version=9.10.2.21, Culture=neutral, PublicKeyToken=e33137c86a38dc06" />
</DbProviderFactories>
</system.data>
</configuration>
Can you try that last part about the app.config?
If you did all this, and it still doesn't work, then it'll be an ADS version mismatch. Versions of:
Advantage Database Server
.NET Advantage Provider
XML-tag that registers the database provider in your app.config
have to match.

Entity Framework hangs when I try to get values

My program hangs when it gets values using Entity Framework. Here is my simple code:
LearningEnglishEntities db2 = new LearningEnglishEntities();
List<tb_Words> searchedItems = db2.tb_Words.ToList(); // it hangs here
It's not an async method. There are solutions about async but I didn't find any solution to fix my problem.
It doesn't respond, it's waiting forever. All my code was running until 2 days ago. I didn't type or do anything and this bug happened (short video is here)
I have tried these things so far:
I removed Entity Framework model from my solution and I added it again
I created a new program and I used exactly same codes and model (it worked):
LearningEnglishEntities1 db = new LearningEnglishEntities1();
List<tb_Words> sample = db.tb_Words.ToList(); // It worked
I cleaned my solution
I typed this code:
var query = from item in db.tb_Words select item; // It hangs the same way
I checked this code is not run by another thread:
bool query0 = this.InvokeRequired;
if (!query0)
{
LearningEnglishEntities db2 = new LearningEnglishEntities();
List<tb_Words> searchedItems = db2.tb_Words.ToList(); // It still hangs
}
I changed my Entity Framework 6.0x version to 5.0x but it didn't
work.
I completely copied all files and pasted to a new project. It ran but it didn't work
I restarted Microsoft Distributed Transaction Coordinator Service and checked startup type is Automatically. It didn't work.
Strangely, it works on other projects but it hangs on this project. I haven't found any solution to fix this bug. Do you think what should i do?
Also My Connection String is :
<connectionStrings><add name="LearningEnglishEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-REKGVD4\SQLEXPRESS;initial catalog=LearningEnglish;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
Thank you
After all things, I was able to find a solution but I don't know the reason. Using Entity Framework Code First solved my problem. It is not good for my project but i have to use it.

Make C# Console App recognize manually edited changes in .exe.config file

I successfully wrote a C# console application that collects .XML or .ZIP files from different locations and copies them to a single destination. Those locations are stored in the settings as User-scoped settings (for instance, "Folder01 C:\Data1\" and "Folder02:\Data2"). As you probably already know, building the project generates a [ProjectName].exe.config file in the /bin/Debug folder.
Now, the issue is that I cannot get the console app to recognize any changes that I made in the .exe.config file. Say, I want to add "Folder 03 C:\Data3\" to the settings or edit "Folder02" path to "C:\DataEdited\", the console app will still loop through the settings as initially set up in the code ("Folder01 C:\Data1\" and "Folder02 C:\Data2\").
I also noticed that the console app still runs even after deleting the .exe.config file, as if it does not rely on the file at all. I would like to make changes without having to open the project in Visual Studio and edit locally.
Is that possible?
EDIT:
In response to the request of the Settings that I created and code for getting folder paths, see image image below:
Here is the code:
string[] acceptedExtensions = new[] { ".xml", ".zip" };
string[] settingsToSkip = new[] { "RootFolder", "ArchiveFolder" };
// Collect data
var filteredSettings = Properties.Settings.Default.Properties
.Cast<SettingsProperty>()
.Where(p => !settingsToSkip.Contains(p.Name));
filteredSettings collects Folder01, Folder02, Folder03 and Folder04 and I loop through those to find files with acceptedExtensions.
I believe you expected this feature of c# ConfigurationManager. You might have deleted *.exe.config after your application is started. *.exe.config is not locked or needed after app starts unless you call configurationmanager.refreshsection() method.
Reloading configuration without restarting application using ConfigurationManager.RefreshSection
https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.refreshsection?view=netframework-4.7.2
Thumbs up and mark it if it helped you!
How I have done it in my production code is that I have added to my App.config with my Visual Studios and made it have the format of:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="AConnection" value="127.0.0.1"/>
<add key="Folder01" value="L:\Path\To\A\Thing"/>
<add key="Folder02" value="L:\Path\To\ASecond\Thing"/>
<add key="Folder03" value="L:\Path\To\AThird\Thing"/>
<add key="Folder04" value="L:\Path\To\AFourth\Thing"/>
</appSettings>
</configuration>
Where the <add key="" value="">s are whatever you wish to name them and the values is the path to the correct file.
Assigning:
You can then assign these to variables:
string conStr = ConfiurationManager.AppSettings["AConnection"];
string strFolder1 = ConfigurationManager.AppSettings["Folder01"];
string strFolder2 = ConfigurationManager.AppSettings["Folder02"];
string strFolder3 = ConfigurationManager.AppSettings["Folder03"];
string strFolder4 = ConfigurationManager.AppSettings["Folder04"];

Unable to find connection 'MyConnName' for object 'Web.config' in Table Adapter configure Properties

I want to change the query in table adapter but it's not opening & throwing an error "Configure table Adapter Failed" & in property of connectionString it says "Unable to find connection 'ConnStringName' for object 'Web.config'. The connection string could not be found in application settings, or the data provider associated with the connection string could not be loaded"
I have been looking for a solution for this problem for a long time. Thankfully I found a solution that worked for me.
Close the dataset window with the error.
Right click the dataset in the solution explorer.
Select “Open with…” from the context menu.
Select “Source Code (Text) Editor” from the list and press the “OK”
button.
Near the top of the file, you’ll see a element with several elements within it. Most datasets should only have one element. If you are having trouble like I’ve described above, you’ll have at least two and one will be incorrect. Delete it or otherwise fix it, save the file and reopen normally.
This is the page where I found it out.
See the complete answer here
I faced the same problem which is actually a nightmare and triyed Lorena solution and it was not enough to solve the problem.
The missing part is to modify the Dataset using the XML editor changing the DefaultConnectionIndex to be 0 like this:
<DataSource DefaultConnectionIndex="0"
FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass,
Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-
microsoft-com:xml-msdatasource">
thanks to Don who pointed this
https://social.msdn.microsoft.com/Forums/windows/en-US/08a48cad-619d-4421-b584-f2b5550ba6c5/dataset-designer-quotunable-to-find-connection-myconn-mysettings1-for-object-mysettingsquot?forum=winformsdatacontrols
Seems like there no ConnStringName parameter in connectionString section of Web.config
<connectionStrings>
<add name="ConnStringName" providerName="" connectionString=""/>
</connectionStrings>
Updated:
The problem is in missing reference to System.Data.OracleClient. To solve this just add reference on missing provider.
Well Same problem I faced in Windows Forms, I just opened Settings.settings file, found the "ConnectionString" and repaired it.
(As you click in Value field of ConnectionString a button [...] appears in last of Value field click it and repair/test your connection again, in my case I re-entered password again.) .
Hope This Helps.!
ConnStringName is case-sensitive.

Why is my Connection String only working in Dev?

See DGibbs answer below.
I can't have the config file saved with the EXE, as this is present on each user's desktop, so it seems I am unable to store the password in the config file and will have to come up with some other solution.
I have an app that needs to run a CMD command as an administrator. To achieve this, I stored the password in a connection string in app.config:
<connectionStrings>
<add name="mypw" connectionString="PASSWORD" />
</connectionStrings>
I am then able to call this in my Cmd class as a SecureString:
private static SecureString pw()
{
string connectionString = ConfigurationManager.ConnectionStrings["mypw"].ConnectionString;
SecureString ss = new SecureString();
foreach (char c in connectionString)
{
ss.AppendChar(c);
}
return ss;
}
When I run the app from VS on my machine with debugging (F5), it works fine and the password is retrieved. However, when running it in a development environment I see the exception Object Reference not set to an instance of an object, and from my own debugging I can see that this is happening at this line:
string connectionString = ConfigurationManager.ConnectionStrings["mypw"].ConnectionString;
Can anyone please explain why the app is able to retrieve the connection string on my machine but not when deployed elsewhere? Does the app.config file change when publishing the app?
Few things, don't use <connectionStrings>, this is typically used to store credentials for a db connection, it doesn't make sense here. Try using AppSettings within the App.config file e.g
<appSettings>
<add key="mypw" value="password" />
</appSettings>
You can retrieve the value like this:
string pw = ConfigurationSettings.AppSettings["mypw"];
Finally, make sure you have the config file deployed, it should be [ApplicationName].exe.config and not App.Config. If it doesn't appear, check the Copy to output directory setting, make sure it's set to Copy Always.

Categories