Alter database in Entity Framework migration - c#

I want to enable broker for my database in an Entity Framework migration. I add a migration to my project and write this code in the Up method :
Sql("ALTER DATABASE current SET ENABLE_BROKER", true);
This code runs correctly for SQL Server 2014, but when I change my target database to SQL Server 2008 R2 Express, I get this error:
Incorrect syntax near the keyword 'current'
How do I change the code to run properly for all type of SQL Server instances?

Before SQL 2012 you have to use the database name. Something like this batch:
declare #sql nvarchar(max) = N'ALTER DATABASE ['+db_name()+N'] SET ENABLE_BROKER;'
exec( #sql );
should work.

Related

Entity Framework SaveChanges doesn't work

I'm trying to save some records into a SQL Server database using EF6 and this code:
_db.MyEntity.Add(item);
_db.SaveChanges();
I can see the code/stored procedure in SQL Server Profiler (RPC:Completed) so it's being executed and when I run the same SQL manually in Management Studio, then the insert works OK (item has been inserted without errors).
Is there a reason why this doesn't work?
Am I missing something (DbContext is OK as I have _db.Remove(item) few lines above that works fine)?
Ok, so the issue was caused by data type. SQL identity column was INT and in API model it was LONG.
As I said, I wasn't getting any errors on executions and the sql code copied from sql server profiler worked when executed.
Changing LONG to INT32 in API model resolved this issue for me (insert from API works).

How to export database and import it locally by C# code?

How to "clone" a database from a remote server to LocalDB database by a C# application? No relationships back to the remote database are needed.
Background
Application is written in C# using .NET 4.5.2 and supports two modes - online which connects to a remote MS SQL Server database, and offline which connects to a LocalDB database. The application primarily targets newer versions of the servers (if it matters, supporting only version 2014 is ok).
Before the user goes offline it should ask the application to clone the remote database to the LocalDB database (the local database is completely overwritten). The local database should be independent on the remote database, i.e. no slave nor replication.
Both the online and offline connection string contains name of the respective database. The application itself has no direct knowledge of the database name nor of the table names as this is managed by the connection strings and by the Entity Framework.
Question
How to "clone" the remote database to a LocalDB database (the remote database name and the LocalDB database name might be different)?
I prefer a solution which does not require to launch an external program, but this is not a hard requirement.
Issues
Copying through Entity Framework no tracking entities is unacceptable slow.
I am aware of the BACKUP DATABASE and RESTORE DATABASE commands, but I have found the following difficulties:
They require me to specify the name of the database. Is there a way how to default them to the initial database specified as part of the connection string?
The RESTORE DATABASE command contains names and paths of the respective data files on the disc (MOVE parts). Is there a way how to process it with specifying just the database name without providing the data files path? Or how to get the data files paths via SQL commands (to get the file names, I will just create a blank database, got the file names, optionally drop the database and use the retrieved file names)?
Is there a better way doing this?
I use a stored procedure i created, but first you need to create a linked server:
IF EXISTS(SELECT name FROM sys.servers WHERE name = 'SERVER')
BEGIN--
EXEC sp_dropserver 'SERVER', 'droplogins'
END
/****** Object: LinkedServer [SERVER] create LinkedServer ******/
EXEC master.dbo.sp_addlinkedserver
#server = N'SERVER',
#srvproduct=N'SQLNCLI',
#provider=N'SQLNCLI',
#datasrc=N'192.168.1.1' -- IP address of a server
/* Add login data*/
EXEC sp_addlinkedsrvlogin
#useself='FALSE',
#rmtsrvname='SERVER',
#rmtuser='User',
#rmtpassword='Pass'
Then you can create stored procedure on local server or execute the query directly from application, also for safety I am using a transaction in this example:
USE [DB]
GO
/****** Object: StoredProcedure [dbo].[backupdatabase] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[backupdatabase]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
TRUNCATE TABLE [dbo].[table_1]
INSERT INTO [dbo].[table_1]
SELECT * FROM [SERVER].[DB].[dbo].[table_1]
TRUNCATE TABLE [dbo].[table_2]
INSERT INTO [dbo].[table_2]
SELECT * FROM [SERVER].[DB].[dbo].[table_2]
TRUNCATE TABLE [dbo].[table_3]
INSERT INTO [dbo].[table_3]
SELECT * FROM [SERVER].[DB].[dbo].[table_3]
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity int
SELECT #ErrMsg = ERROR_MESSAGE(),
#ErrSeverity = ERROR_SEVERITY()
RAISERROR(#ErrMsg, #ErrSeverity, 1)
END
END CATCH
END

How can I insert in Fluent NHibernate using SQL Server 2012 with sequences?

I'm trying to use SQL Server 2012 + Fluent NHibernate + sequences.
I have a created sequence in SQL Server 2012, I've configured the sequence in my table like in this link sequence as a default value for a column in SQL Server
But I'm trying to insert a record and It does not work, I receive the error "null identifier".
Is there any example about how to configure Fluent NHibernate working with SQL Server 2012 sequences?
Regards
Take a look a this site, here they use a default sequence.
this.Id(x => x.Id)
.GeneratedBy.SeqHiLo("mysequence", "1000")
.Default("next value for mysequence");

What does a *.sql file contain

In Vsual Studio => Server Explorer I created a new SQL Server database (dbo) and I right clicked on the option "publish to provider".
It generated a file with sql extension which includes sql commands (SELECT, UPDATE).
I want to know what does this file contain.
Is it the whole database?
Can I import this file to SQL Server Management Studio later?
And does it store everything in database (relations, default values, rules)?
I have written some of the text from the file
/****** Object: ForeignKey [FK__aspnet_Me__Appli__21B6055D] Script Date: 06/30/2013 12:01:32 ******/
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo]. [FK__aspnet_Me__Appli__21B6055D]') AND parent_object_id = OBJECT_ID(N'[dbo]. [aspnet_Membership]'))
ALTER TABLE [dbo].[aspnet_Membership] DROP CONSTRAINT [FK__aspnet_Me__Appli__21B6055D]
GO
/****** Object: ForeignKey [FK__aspnet_Me__UserI__22AA2996] Script Date: 06/30/2013 12:01:32 ******/
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo]. [FK__aspnet_Me__UserI__22AA2996]') AND parent_object_id = OBJECT_ID(N'[dbo]. [aspnet_Membership]'))
ALTER TABLE [dbo].[aspnet_Membership] DROP CONSTRAINT [FK__aspnet_Me__UserI__22AA2996]
GO
/***
i clicked [...] can i import this file to sql server management studio later?
Then look at the manual for what you clicked on:
The Database Publishing Wizard in Visual Studio enables you to deploy a SQL Server database (both schema and data) to a hosting environment. You can run the wizard by right-clicking a database in Server Explorer and then clicking Publish to provider.
The tool supports the following ways to deploy a database:
It can generate a single SQL script file that you can manually run on the target server to re-create the database schema and the database contents.
So, yes.
This file contains a list of SQL statements that will transform the DB you selected during the process.
This file will work only for a DB in the same state as the one you selected.
If you will run this process twice, the script that will be generated will be different, since the first script changed your db, and some operations will not be performed.
This file does not contain all the data in the DB.

Couldn't connect to sql server database from ado.net

I wrote simple sql script that creates my database:
create database [MaterialStream];
exec sp_addlogin N'MaterialStreamLogin', N'123', N'MaterialStream'
exec sp_adduser N'MaterialStreamLogin', N'MaterialStreamUser', N'db_owner'
And then couldn't connect to my database from ADO.NET. How can I set up credentials for my user?
Have you tried logging on as that user using Management Studio? It's possible it's defaulted to requesting a password change on first login or similar.

Categories