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

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.

Related

[MS-Access][ODBC] Can't delete an line on a form, ODBC delete on a linked table failed

I have a form that is linked to an ODBC (MS SQLServer), that is displaying a result of a VIEW, when I try to delete a record, I'm invoking a function at VBA level
Form_BeforeDelConfirm(Cancel As Integer, Response As Integer){
If (IsNull(Text104.value) = False) Then
Dim deleteLabel As DAO.QueryDef
Set deleteLabel = CurrentDb.CreateQueryDef("")
deleteLabel.Connect = CurrentDb.TableDefs("KontrollWerte").Connect
If (InStr(QuerySave, "KontrollWerteVIEW") <> 0) Then
deleteLabel.sql = "delete from KontrollWerte_Label where Kontrolle_Label_ID = " & Text104.value
End If
Close
End If
}
Error shown:
[Microsoft][SQL Server Native Client 11.0][SQL Server] View or function 'dbo.KontrollwerteVIEW' is not updatable because the modification affects multiple base tables. (#4450)
This error is okay, as the view is a select with multiple tables.
It seems the function is not called at all, and the "default" delete function of the MS Access is being called, there is a way to say to MS Access don't do the default delete and instead execute my sql statement inside of the Form_BeforeDelConfirm function?
Thanks!
I tried to change when the call of function is called, but no luck.
You have to ensure that the view allows updates.
When you link a table, and it is a view?
The during the creating of the table link, then you will see this prompt:
First, we select the "view" when linking that "view/table"
and note I also checked the Save password option.
Then next we get/see this:
DO NOT skip the above prompt. If you don't select the PK column for that view, then it will be read only.
FYI:
The above prompt to save password, and the above prompt to select the PK when linking to that view?
It DOES NOT appear on re-link, ONLY when adding a new link!!!!
So, that's why I stated to delete the link to sql server (not just re-link and not just re-fresh table link, but Adding for first time are the key instructions here).
So, yes, views are and can be up-datable, but you MUST answer the above prompt during the linking process in Access, or the result is a read-only table.

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

Database applies ALL previous migrations on update and NOT just the new one

I'm developing a website which, as of current, both has a production and a test database.
The production database is hosted externally while the test database is hosted locally.
Whenever I make changes to my database I apply the changes through a migration.
After having added a new migration I run the update-database command on both my production and test database to keep them in sync.
I applied the migration just fine to my production database, however, when I wanna apply the migration to my test database I see that it attempts to apply ALL the previous migrations (and not just the new one):
Here is the output:
Applying explicit migrations: [201603230047093_Initial,
201603232305269_AddedBlobNameToImage,
201603242121190_RemovedSourceFromRealestateDbTable,
201603311617077_AddedSourceUrlId,
201604012033331_AddedIndexProfileAndFacebookNotifications,
201604012233271_RemovedTenantIndexProfile,
201604042359214_AddRealestateFilter]. Applying explicit migration:
201603230047093_Initial. System.Data.SqlClient.SqlException
(0x80131904): There is already an object named 'Cities' in the
database.
Obviously it fails since the current state of the database is at the second latest migration. However I wonder why it attempts to apply ALL the previous migrations?
Unlike the production database (which has had all the migrations applied one at a time), the test database was deleted and created at the previous migration so its migration history table only contains one row:
201604012239054_InitialCreate
(I assume InitialCreate is an auto generated name of all the previous migrations combined).
In summary:
Why is the test database trying to apply ALL the previous migrations instead of just the newly added?
EDIT:
When running COMMMAND I get the follow output script:
DECLARE #CurrentMigration [nvarchar](max)
IF object_id('[dbo].[__MigrationHistory]') IS NOT NULL
SELECT #CurrentMigration =
(SELECT TOP (1)
[Project1].[MigrationId] AS [MigrationId]
FROM ( SELECT
[Extent1].[MigrationId] AS [MigrationId]
FROM [dbo].[__MigrationHistory] AS [Extent1]
WHERE [Extent1].[ContextKey] = N'Boligside.Migrations.Configuration'
) AS [Project1]
ORDER BY [Project1].[MigrationId] DESC)
IF #CurrentMigration IS NULL
SET #CurrentMigration = '0'
IF #CurrentMigration < '201603230047093_Initial'
(it proceeds making if statements for each previous migration)
The current migrations table in my database looks the following (note that the first row is for a logging framework so it's not related):
One issue that can cause migrations to rerun is if your context key changes which can happen during refactoring. There are a couple of ways to solve this:
1) Update the old records in __MigrationHistory with the new values:
UPDATE [dbo].[__MigrationHistory]
SET [ContextKey] = ‘New_Namespace.Migrations.Configuration’
WHERE [ContextKey] = ‘Old_Namespace.Migrations.Configuration’
2) You can hard code the old context key into the constructor of your migration Configuration class:
public Configuration()
{
AutomaticMigrationsEnabled = false;
this.ContextKey = “Old_Namespace.Migrations.Configuration”;
}
Here is a good article on how migrations run under the hood: https://msdn.microsoft.com/en-US/data/dn481501?f=255&MSPPError=-2147217396
See also http://jameschambers.com/2014/02/changing-the-namespace-with-entity-framework-6-0-code-first-databases/

LinqToSQL not updating database

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.

PowerBuilder DSN Creation

I am new to PowerBuilder.
I want to retrieve the data from MSAccess tables and update it to corresponding SQL tables. I am not able to create a permanent DSN for MSAccess because I have to select different MSAccess files with same table information. I can create a permanent DSN for SQL server.
Please help me to create DSN dynamically when selecting the MSAccess file and push all the tables data to SQL using PowerBuilder.
Also give the full PowerBuilder code to complete the problem if its possible.
In Access we strongly suggest not using DSNs at all as it is one less thing for someone to have to configure and one less thing for the users to screw up. Using DSN-Less Connections You should see if PowerBuilder has a similar option.
Create the DSN manually in the ODBC administrator
Locate the entry in the registry
Export the registry syntax into a .reg file
Read and edit the .reg file dynamically in PB
Write it back to the registry using PB's RegistrySet ( key, valuename, valuetype, value )
Once you've got your DSN set up, there are many options to push data from one database to the other.
You'll need two transaction objects in PB, each pointing to its own database. Then, you could use a Data Pipeline object to manage the actual data transfer.
You want to do the DSNLess connection referenced by Tony. I show an example of doing it at PBDJ and have a code sample over at Sybase's CodeXchange.
I am using this code, try it!
//// Profile access databases accdb format
SQLCA.DBMS = "OLE DB"
SQLCA.AutoCommit = False
SQLCA.DBParm = "PROVIDER='Microsoft.ACE.OLEDB.12.0',DATASOURCE='C:\databasename.accdb',DelimitIdentifier='No',CommitOnDisconnect='No'"
Connect using SQLCA;
If SQLCA.SQLCode = 0 Then
Open ( w_rsre_frame )
else
MessageBox ("Cannot Connect to Database", SQLCA.SQLErrText )
End If
or
//// Profile access databases mdb format
transaction aTrx
long resu
string database
database = "C:\databasename.mdb"
aTrx = create transaction
aTrx.DBMS = "OLE DB"
aTrx.AutoCommit = True
aTrx.DBParm = "PROVIDER='Microsoft.Jet.OLEDB.4.0',DATASOURCE='"+database+"',PBMaxBlobSize=100000,StaticBind='No',PBNoCatalog='YES'"
connect using aTrx ;
if atrx.sqldbcode = 0 then
messagebox("","Connection success to database")
else
messagebox("Error code: "+string(atrx.sqlcode),atrx.sqlerrtext+ " DB Code Error: "+string(atrx.sqldbcode))
end if
// do stuff...
destroy atrx

Resources