Code first filetable in SQL Server - entity-framework

Trying to take advantage of the FileTables feature in SQL Server 2012 in my current MVC5 project. Does anyone have any examples of how to create the file table "table" using code first? All of my tables, indexes, etc. are done using code first and I'd like to continue that practice here.

Unfortunately I cannot help you with FileTable, but this example of FileStream (similar thing in many ways) works quite well.

The decision is available here: "WEB API FILE UPLOAD WITH MS SQL SERVER FILETABLE"
https://damienbod.wordpress.com/2014/04/08/web-api-file-upload-with-ms-sql-server-filetable/

You can add custom SQL in a Code First Migration.
Create a migration Add-Migration
Put In some Custom SQL to Enable Filestreams
Update the db with Update-Database
Example migration with custom SQL:
public partial class AddFileStreamMigration: DbMigration
{
public override void Up()
{
var customSql = #"ALTER DATABASE Photos
SET FILESTREAM (NON_TRANSACTED_ACCESS = FULL)
GO
etc...";
Sql(customSql );
}
public override void Down()
{
//Make sure you put in roll back SQL too!
}
}
```

Related

How to select data from old database and insert it into new one within doctrine migration?

I use 'doctrine/DoctrineORMModule' module for zend framework 3 (MVC). I have configured 'orm_default' and can configure 'orm_old' but don't know how to use 'orm_old' within migration file.
I can do this within migration file:
public function up(Schema $schema) : void
{
$sql = "INSERT INTO `some_table` VALUES ('some_value','','',NULL,NULL,'1');";
$this->addSql($sql);
//...
But in general I need run something like this:
INSERT INTO DB2.T2(id, title, description)
SELECT id, title, description FROM DB1.T1;
How to do that?
If I understand correctly, you'd like to use Doctrine Migrations for two database connections: orm_default and orm_old.
This is possible in Doctrine, but not with the Zend Framework DoctrineORMModule. This is mentioned very shortly in the official documentation: https://github.com/doctrine/DoctrineORMModule/blob/master/docs/migrations.rst#multiple-migration-configurations
The best thing you can do is to use two separate cli-config files with the same database connections, and put the migrations in two seperate folders. You can then use the 'default' doctrine CLI tools (vendor/bin/doctrine migrations:migrate ) to run migrations for the two connections.
Adding this functionality to the DoctrineORMModule was requested, but never implemented. You can read more about it right here:
https://github.com/doctrine/DoctrineORMModule/issues/537

How to Create Custom Stored Procedures Using Code First Fluent API

There are many articles that show how to create Insert, Update, Delete procedures using Code First like this one.
How about custom procedure like this simple select statement:
Select * from Customers
I could make changes to the Up and Down Migration methods, but is there a way to create custom procs using Fluent API directly.
Here is a solution which I don't recommand but If you want to use DbContext.Database, here it is:
using(var db = new MyDbContext(connectionString))
{
db.Database.ExecuteSqlCommand("CREATE PROCEDURE MyProcedure ... END;");
var command = "EXEC MyProcedure;";
IEnumerable<Customer> customers = db.Database.SqlQuery<Customer>(command, null);
}

Alter Database in Entity Framework 6

I have update my EF to EF 6.0.2 in my code I have the following line of code:
applicationDbContext.Database .ExecuteSqlCommand(#"ALTER DATABASE
CURRENT SET RECOVERY FULL;");
After updating I get the following error message:
ALTER DATABASE statement not allowed within multi-statement
transaction.
I have fixed the problem with a TransctionalBehavior like the the code below:
applicationDbContext.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction, #"ALTER DATABASE CURRENT SET RECOVERY FULL;");
My question:
Why I'm getting this error with EF 6?
My fix is a valid fix for the problem or a devil hiding behind this solution?
Is there any other approach to solve the problem?
Any help will be greatly appreciated!?
EF 6 changes the use of transactions with ExecuteSqlCommand
Starting with Entity Framework 6.0, ExecuteSqlCommand() by default will wrap the command in a transaction if one was not already present. There are overloads of this method that allow you to override this behavior if you wish.
EF 5 did not behave the same way. Your fix is appropriate.
You can now specify a TransactionalBehavior flag to instruct EF on how to handle transactions with this command.
var sqlCommand = String.Format("ALTER DATABASE {0} SET SINGLE_USER
WITH ROLLBACK IMMEDIATE");
db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
sqlCommand);
By using the DoNotEnsureTransaction flag, EF will not start a transaction before executing the command. This allows the ALTER DATABASE command to successfully execute.
If you are using Code First approach possible solution is
public partial class AlterDatabase : DbMigration
{
public override void Up()
{
Sql("ALTER DATABASE CURRENT SET RECOVERY FULL", true);
}
public override void Down()
{
}
}

EF code first - Model compatibility cannot be checked because the database does not contain model metadata

I have enabled automatic migrations. Then, I deleted my whole db. Next, i executed Update-database from command console, and it recreated my db. Then, I started my application only to see this error:
Model compatibility cannot be checked because the database does not
contain model metadata. Model compatibility can only be checked for
databases created using Code First or Code First Migrations.
So what exactly is that metadata, and how can I point entity framework to it?
PS. My database contains table named MigrationsHistory.
Here is a detailed description of the possible ways to resolve this which I wrote a while ago...
(not exactly what you're experiencing, hence not a duplicate per se, but with different scenarios in mind)
https://stackoverflow.com/a/10255051/417747
To summarize...
What works for me is to use Update-Database -Script
That creates a script with a 'migration difference', which you can
manually apply as an SQL script on the target server database (and you
should get the right migration table rows inserted etc.).
If that still doesn't work - you can still do two things...
a) remove the migration table (target - under system tables) - as per
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx
comments in there - that should fail back to previous behavior and if
you're certain that your Db-s are the same - it's just going to 'trust
you',
b) as a last resort I used - make a Update-Database -Script of the
full schema (e.g. by initializing an empty db which should force a
'full script'), find the INSERT INTO [__MigrationHistory] records,
just run those, insert them into the database, and make sure that your
databases - and code match,
that should make things run in sync again.
if it helps
Detach your local Database say example 'database1.mdf' from visual studio 'server explorer' and then open SQL server management studio right click on Databases > Attach and then browse the same 'database1.mdf' file .If you doesn't have access then copy&past both the mdf and ldf files into c drive and do attach.
Then open new query window on sql server then do copy your identity tables as like below query.
*'select * into [__MigrationHistory] from Database1.dbo.__MigrationHistory '*
Add this to your context:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}
I use Entity Framework 6 , SQL 2008 R2 , VS 2013.
To solve this problem only use the following procedure :
1) delete existing db ( existing database that created with EF model{code first})
2) Run APP again.
Fore example query code (in Layout):
this code create db if my model is change and search username in user table.
<body>
#{
// Delete && Create ...
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBContext>());
var db = new DBContext();
var SearchingUser = db.Users.Where(c => c.UserName == "qwertyui");
if (SearchingUser.Count() == 0) {
var User = new Users { UserName = "qwertyui",Password = "12345678" };
db.Users.Add(User);
db.SaveChanges();
}
}
#RenderSection("scripts", required: false)
#RenderBody()
</body>
Package Manager Console > Enable-Migrations -EnableAutomaticMigrations
Configure Migrations/Configuration.cs
Package Manager Console > Update-Database

How to affect the column order with Entity Framework Code First Migrations

I'm using Entity Framework 4.3 Code First and trying out the Migrations feature.
If I add a new property to my class and then run Add-Migration from the package manager console window I get something like this:
public override void Up()
{
AddColumn("Products", "Discontinued", c => c.Boolean(nullable: false));
}
I would like to be able to affect the order of the column as I don't want it to just be appended to the table but rather placed at a specific index. I thought I might be able to add it to my modelBuilder configuration, something like:
Property(p => p.Discontinued).HasColumnOrder(2);
but running Update-database does not appear to use it. Can this be done as a migration?
This is just a matter of missing functionality. SQL by itself does not rely on any implicit order of columns (with some exceptions: ORDER BY , ...).
Neither SQL Server nor ORACLE do have a direct SQL DDL command (aka ALTER TABLE...) to move a column around.
Therefore there's no possibility to change the order without high effort (recreate the table). See for example
How To change the column order of An Existing Table in SQL Server 2008
SQL SERVER – Change Order of Column In Database Tables
https://dba.stackexchange.com/questions/61978/how-to-change-the-column-order