ADO.NET to update table in SQL Server 2008 - c#

I am using ADO.NET and trying to update a column value in a table in a SQL Server 2008 database. However the value is not updating. Even though it's update when I debug it in C# code. Here is my code:
using (ADONETClass context = new ADONETClass())
{
List<Invoices> list = context.Invoices.ToList<Invoices>();
foreach (Invoices b in list)
{
b.status = 0;
}
}
Now I debugged the code and saw that context.Invoices.ToList<Invoices>()[0].status is indeed set to zero. But when the program finished running, I open the SQL Server Management Studio and status value there was still 0. Not sure what is going on? Am I missing something?
Thanks
Varun

Are you calling context.SaveChanges()?

Are you using Entity Framework?
I think you're missing a call to context.SaveChanges
In EntityFramework the changes are all just in memory and not written to database until you call SaveChanges

Related

Unable to begin a distributed transaction using Entiy Framework

I'm having the following error executing this piece of code:
private bool _updateList(SysInfo _sysInfo, List<pList> _pList)
{
try
{
foreach (var p in _pList)
{
_context.spUpdatePListApprovalFlow(p.countryID, _sysInfo.User.JobRoleID, p.src, p.id, p.status, _sysInfo.User.Username);
}
return true;
}
catch (Exception ex) //debug only
{
throw; //throws error to the main try catch
}
}
ERROR
The operation could not be performed because OLE DB provider "MSDASQL"
for linked server "AS400_LINKEDSRV" was unable to begin a distributed
transaction.
However, everything works fine when I run the Stored Procedure in SQL Management Studio:
exec [dbo].[spUpdatePListApprovalFlow]
#CountryID = 123456,
#UserTypeID = 23456,
#Src = 1,
#Id = '123456789',
#Status = 30,
#Username = 'username'
I'm tired of digging for an answer nothing works... Few things I've tried:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
insert multiple transactions in the stored procedure
This sp has 2 sub stored procedures on it. One that writes into a table of the application's database, and another that updates a table in as400.
In EF6 stored procedures are called in an explicit transaction, by default. You can turn this off for a particular DbContext instance by changing its configuration after creating it, or for all instances of a DbContext type by changing it in the constructor. EG
using (var db = new Db())
{
db.Configuration.EnsureTransactionsForFunctionsAndCommands = false;
//. . .
}
See: https://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbcontextconfiguration.ensuretransactionsforfunctionsandcommands
Ok, after half a day trying to solve this I've finally solved it.
Resolution
Downgraded from Entity Framework 6 to Entity Framework 5 and the
distribuited transactions error has gone.
Just pay attention, if you're going to do this, you have to change some usings in your code. ( in auto generated code in the Data Model as well)
EF 6 uses
using System.Data.Entity.Core.Objects
EF 5 uses
using System.Data.Objects;
If you don't need distributed transactions you can try to disable them in the settings of the linked server:
EXEC master.dbo.sp_serveroption
#server=N'AS400_LINKEDSRV',
#optname=N'remote proc transaction promotion',
#optvalue=N'false'
Refer to this Microsoft page on Linked Servers.
Your System Administrator and/or DBA will probably need to make changes to address the missing linked server definition to your AS/400 server.
Another possible issue is that the AS/400 server (from IBM) lacks software support for the OLE DB data sources. This too would be something that the System Administration staff may need to address.

Ado.net firebird commit insert new lines to table

I'm adding new lines to a database for our company's "order list" for each order created, using the firebird ado.net client. The code i've written works fine for listing items, but inserting new ones doesn't appear elsewhere (e.g. in flamerobin). What I think is happening is that the transaction isn't being committed, seeing as it's recognised within my code (can't add duplicate values).
Code:
using (FbConnection fbCon = new FbConnection)
{
fbCon.Open();
***command w/ parameterised command string***
using (FbTransaction fbTrans = fbCon.BeginTransaction())
using FbCommand orderCommand = new FbCommand(cmdString, fbCon, fbTrans)
{
***Adding parameters and values***
try
{
int recordsAffected = orderCommand.ExecuteNonQuery();
fbTrans.Commit();
}
catch (FbException E)
{
fbTrans.Rollback();
fbCon.Close();
throw E
}
}
recordsAffected returns 1 but I am not able to see the updated values in flamerobin or the db management program. Am i missing something?
If anyone else runs into this problem, it's in Visual Studio's debugging settings. https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx explains pretty clearly, but basically VS makes a copy of your database in bin/Debug of your project (Ostensibly to not mess with your data) but if you actually need to use/view the data externally, either link your external application to the debug database (e.g. flamerobin). You may also need to set your project database settings to Copy if Newer if you want your updates to stay, as the default setting copies the database into the folder each time you run your c# app.

Modify .mdf file from a wpf application using C#

I am using VS2010 , and I am building a simple wpf application using C#
I have built a database using SQL Server 2008
in my application I created a LINQ to SQL class and created a dbml file
then I created a datacontect and did everything right
BUT
when I can't aaccess my database file everytime I try to , I mean when I insert anew row in my datacontexct I can check it and see it but when I look in my mdf file I can't find anything
I think that my datacontexct must be connected to my database file somehow
please help me because I seriously need it
The connection string, that is passed to the datacontext, references the MDF.
// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(#"northwnd.mdf");
var cityNameQuery =
from cust in nw.Customers
where cust.City.Contains("London")
select cust;
foreach (var customer in cityNameQuery)
{
if (customer.City == "London")
{
customer.City = "London - Metro";
}
}
// you must call this this commit the changes
nw.SubmitChanges();
Call .SubmitChanges() on your DataContext after adding an item.

Can't update rows in my database using Entity Framework...?

Okay, this is really weird. I made a simple database with a single table, Customer, which has a single column, Name. From the database I auto-generated an ADO.NET Entity Data Model, and I'm trying to add a new Customer to it like so:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main()
{
Database1Entities db = new Database1Entities();
Customer c = new Customer();
c.Name = "Harry";
db.AddToCustomer(c);
db.SaveChanges();
}
}
}
But it doesn't persist Customer "Harry" to the database! I've been scratching my head for a while now wondering why such a simple operation doesn't work. What on earth could be the problem!?
EF requires that you have a unique index for many operations.
Try adding an identity field (primary key) to your table. Delete and recreate your model and try again.
Edit:
It looks like you are running this from a console app.
Do you have a connection string in the app.config file?
Do you have more than one project in your solution?
Are you getting any exceptions?
Edit2:
Next things to try:
Use SQL Server profiler to see what is being sent to the database
Open the EF model in an editor to see the xml, check if there are any errors
Place db in a using statement to ensure the connection/transaction is closed cleanly before process exit.
OK, here's a longshot. Are you sure your connection string is pointing to the right place? And the connection is functioning?
You can verify it by using SQL Server Management Studio to add some records to your test database, and then do something like
foreach (Customer c in db.Customers)
{
Console.WriteLine(c.Name);
}
Make sure that the "Copy to Output Directory" property of the database file is not set to "Copy always." If it is, every time you rebuild the application, the database may be clobbered with a pristine copy.
See: Entity Framework not flushing data to the database

Is there a way to set the DB as Single User Mode in C#?

I have a WPF app that updates my database from an in-code entity model. There may be instances that it updates the DB while there are users connected and I would like to put it in Single-User-Mode to avoid errors.
I would also like to avoid using sql. I am aware that I can run sql using:
DataContext.ExecuteCommand("ALTER DATABASE...")
I would rather use a command in a C# library to do this but I dont know where to look.
Is there a way to set the DB to SUM without using SQL?
So I used the SMO server objects like this:
Server server = GetServer();
if (server != null)
{
Database db = server.Databases[Settings.Instance.GetSetting("Database", "MyDB")];
if (db != null)
{
server.KillAllProcesses(db.Name);
db.DatabaseOptions.UserAccess = DatabaseUserAccess.Single;
db.Alter(TerminationClause.RollbackTransactionsImmediately);
The problem was that this opened a different connection than my datacontext thus kicking myself off and not letting me access the DB. In the end I had to revert to using SQL.
You can use SQLDMO to manage SQL Server objects.
http://msdn.microsoft.com/en-us/library/ms162169.aspx

Categories

Resources