LinqToSQL not updating database - sql-server

I created a database and dbml in visual studio 2010 using its wizards. Everything was working fine until i checked the tables data (also in visual studio server explorer) and none of my updates were there.
using (var context = new CenasDataContext())
{
context.Log = Console.Out;
context.Cenas.InsertOnSubmit(new Cena() { id = 1});
context.SubmitChanges();
}
This is the code i am using to update my database. At this point my database has one table with one field (PK) named ID.
**INSERT INTO [dbo].Cenas VALUES (#p0)
-- #p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build:
4.0.30319.1**
This is LOG from the execution (printed the context log into the console).
The problem i'm having is that these updates are not persistent in the database. I mean that when i query my database (visual studio server explorer -> new query) i see the table is empty, every time.
I am using a SQL Server database file (.mdf).
EDIT (1): Immediate Window result
context.GetChangeSet()
{Inserts: 1, Deletes: 0, Updates: 0}
Deletes: Count = 0
Inserts: Count = 1
Updates: Count = 0
context.GetChangeSet().Inserts
Count = 1
[0]: {DBTest.Cena}

If you construct a DataContext without arguments, it will retrieve its connection string from your App.Config or Web.Config file. Open the one that applies, and verify that it points to the same database.

Put a breakpoint on context.SubmitChanges(); and in your immediate window in VS, do:
context.GetChangeSet();
There is an inserts property and it should have one record. That will help tell if its queuing up an insert.
HTH.

Related

SQL Server : get messages from referenced entities procedure in code

I'm running big dependency scan on legacy db and see that some objects have obsolete ref links, if you run this code in SSMS for View that points to not existing table like in my case, you will get your output on Results tab AND error info in Messages . Like in my case below.
I tried to check all env things I know and output of this stored procedure, but didn't see any indication.
How I can capture this event as I'm running this in looped dynamic SQL script and capture output in my table for further processing?
Updated:
it just text in Message box ,on error, you still have output on
Results tab
this is sp, it loop thru object list I took from sys.object and run this string as my sample to get all dependencies, load all into table. This call to
sql_reference_entities is the only way to get inter database
dependency on column level. So I need stick to this 100$>
--
Select *
From sys.dm_sql_referenced_entities('dbo.v_View_Obs_Table','Object')
--
----update------
This behavior was fixed in SQL Server 2014 SP3 and SQL Server 2016 SP2:
Starting from Microsoft SQL Server 2012, errors raised by
sys.dm_sql_referenced_entities (such as when an object has undergone a
schema change) cannot be caught in a TRY...CATCH Transact-SQL block.
While this behavior is expected in SQL Server 2012 and above, this
improvement introduces a new column that's called is_incomplete to the
Dynamic Management View (DMV).
KB4038418 - Update adds a new column to DMV sys.dm_sql_referenced_entities in SQL Server 2014 and 2016
----update-------
The tldr is that you can't capture these on the server side, and must use a client program in C#, PowerShell or some other client that can process info messages.
That DMV is doing something strange that I don't fully understand. It's generating errors (which a normal UDF is not allowed to do), and those errors do not trigger a TRY/CATCH block or set ##error. EG
create table tempdb.dbo.foo(id int)
go
create view dbo.v_View_Obs_Table
as
select * from tempdb.dbo.foo
go
drop table tempdb.dbo.foo
go
begin try
Select * From sys.dm_sql_referenced_entities('dbo.v_View_Obs_Table','Object')
end try
begin catch
select ERROR_MESSAGE(); --<-- not hit
end catch
However these are real errors, as you can see running this from client code:
using System;
using System.Data.SqlClient;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
using (var con = new SqlConnection("Server=.;database=AdventureWorks;integrated security=true"))
{
con.Open();
con.FireInfoMessageEventOnUserErrors = true;
con.InfoMessage += (s, a) =>
{
Console.WriteLine($"{a.Message}");
foreach (SqlError e in a.Errors)
{
Console.WriteLine($"{e.Message} Number:{e.Number} Class:{e.Class} State:{e.State} at {e.Procedure}:{e.LineNumber}");
}
};
var cmd = con.CreateCommand();
cmd.CommandText = "Select * From sys.dm_sql_referenced_entities('dbo.v_View_Obs_Table','Object')";
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read() || (rdr.NextResult() && rdr.Read()))
{
Console.WriteLine(rdr[0]);
}
}
Console.ReadKey();
}
}
}
}
outputs
Invalid object name 'tempdb.dbo.foo'.
Invalid object name 'tempdb.dbo.foo'. Number:208 Class:16 State:3 at v_View_Obs_Table:4
0
The dependencies reported for entity "dbo.v_View_Obs_Table" might not include references to all columns. This is either because the entity references an object that does not exist or because of an error in one or more statements in the entity. Before rerunning the query, ensure that there are no errors in the entity and that all objects referenced by the entity exist.
The dependencies reported for entity "dbo.v_View_Obs_Table" might not include references to all columns. This is either because the entity references an object that does not exist or because of an error in one or more statements in the entity. Before rerunning the query, ensure that there are no errors in the entity and that all objects referenced by the entity exist. Number:2020 Class:16 State:1 at :1

ASP.NET Core issue with Update record in Sql

I am using ASP.NET Core and SQL Server . When trying to update a record in the database I am getting this following error message:
Database operation expected to affect 1 row(s) but actually affected 39 row(s).
I will past the code below, but the part that is very confusing is that the "where" statement is using the tables primary key -- there is no way that there is more than 1 record with the same key -- which I verified several times.
using (var transaction = _ctx.Database.BeginTransaction())
{
var sql = #"Update [Policies] SET DateInvalid = #DateTimeNow Where EntryNum = #EntryNum";
_ctx.Database.ExecuteSqlCommand(sql,
new SqlParameter("#DateTimeNow", DateTime.Now),
new SqlParameter("#EntryNum", existing.EntryNum) );
_ctx.SaveChanges();
transaction.Commit();
}

pyODBC and SQL Server 2008 and Python 3

I have pyODBC installed for Python 3.2 and I am attempting to update a SQL Server 2008 R2 database that I created as a test.
I have no problem retrieving data and that has always worked.
However when the program performs a cursor.execute("sql") to insert or delete a row then it does not work - no error, nothing. The response is as if I am successful updating the database but no changes are reflected.
The code below essentially is creating a dictionary (I have plans for this later) and just doing a quick build of a sql insert statement (which works as I testing the entry I wrote to the log)
I have 11 rows in my table, Killer, which is not being affected at all, even after a commit.
I know this is something dumb but I can't see it.
Here is the code:
cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=PHX-500222;DATABASE=RoughRide;UID=sa;PWD=slayer')
cursor = cnxn.cursor()
# loop through dictionary and create insert entries
logging.debug("using test data to build sql")
for row in data_dictionary:
entry = data_dictionary[row]
inf = entry['Information']
dt = entry['TheDateTime']
stat = entry['TheStatus']
flg = entry['Flagg']
# create sql and set right back into row
data_dictionary[row] = "INSERT INTO Killer(Information, TheDateTime, TheStatus, Flagg) VALUES ('%s', '%s', '%s', %d)" % (inf, dt, stat, flg)
# insert some rows
logging.debug("inserting test data")
for row in data_dictionary.values():
cursor.execute(row)
# delete a row
rowsdeleted = cursor.execute("DELETE FROM Killer WHERE Id > 1").rowcount
logging.debug("deleted: " + str(rowsdeleted))
cnxn.commit
Assuming this isn't a typo in the post, looks like you're just missing parentheses for the Connection.commit() method:
...
# delete a row
rowsdeleted = cursor.execute("DELETE FROM Killer WHERE Id > 1").rowcount
logging.debug("deleted: " + str(rowsdeleted))
cnxn.commit()

Setting SQL Server DateTime value in F# 3

I have a F# 3.0 program using typeproviders that I am building in Visual Studio 11. I have a SQL Server 2012 database with a table called Article that has a DateTime column Harvest_Time (not null).
In my program I have:
let newrec = new dbSchema.ServiceTypes.Article( Article_Id = System.Convert.ToInt64(ai))
newrec.Url <- art.Item("url").InnerText
newrec.Source <- art.Item("source").InnerText
newrec.Harvest_time = DateTime.Now
db.Article.InsertOnSubmit(newrec)
db.DataContext.SubmitChanges()
which fails because the value of the Harvest_time column is not being set. If I comment out that line the record is inserted just fine. The failure is on the SubmitChanges() where it complains that the datetime value is not set. No other errors are produced.
What am I doing wrong?
I see the error:
I should have used <- rather than = when assigning the value to newrec.Harvest_time.
I am new to F# (I am primarly a C# coder) and just made a silly misttake.
Program works fine now.

SQL Server CE database and ADO.Net Entity Framework - data not saving

I have a SQL Server CE database file and I have ADO.NET Entity Framework object named History. I perform the following to get the latest ID:
var historyid = (from id in db.Histories // Get the current highest history Id
select (Int32?)(id.Id)).Max();
HistoryID = Convert.ToInt32(historyid);
if (HistoryID == 0) // No current record exists
{
HistoryID = 1; // Set the starter history Id
}
(Not the best way, but it is just to test).
This works well and returns the correct value (If I manually enter an ID of 1, it returns 1, same with 2 etc..)
The issue is with the following code:
History history = new History();
history.Id = 1;
history.SoftwareInstalled = "test";
db.AddToHistories(history);
db.SaveChanges();
The above works and runs through fine, but the changes are not saved to the database! Why is this?
Here is my db variable: dbDeSluggerEntities db = new dbDeSluggerEntities();
Thanks.
Edit: Here is an update: I noticed when I run the program and debug it, it shows that a history has been created and inserted and also gives an error of the primary key already existing, this happens each time I run the application (over and over). However, when I go to server explorer and right click the db and select 'Show Table Data' it shows no data.. When the program is run again, there is no primary key error or history's showing in the debug!
I was having exactly the same problem. By default the database is copied into your bin folder when you run the app and that is used.
My solution was to go into the properties of the db and set it to never copy and to put a full file path to the database in the connection string in the apps config file.

Resources