EF Code First #4
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۲/۱۷ ۱۳:۴۹:۰۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
Detected database created with a database initializer. Scaffolded migration '201205050805256_InitialCreate'
corresponding to current database schema. To use an automatic migration instead, delete the Migrations
folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
namespace EF_Sample02.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<EF_Sample02.Sample2Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(EF_Sample02.Sample2Context context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
namespace EF_Sample02.Migrations
{
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"Users",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
LastName = c.String(),
Email = c.String(),
Description = c.String(),
Photo = c.Binary(),
RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
Interests_Interest1 = c.String(maxLength: 450),
Interests_Interest2 = c.String(maxLength: 450),
AddDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"Projects",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(maxLength: 50),
Description = c.String(),
RowVesrion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
AddDate = c.DateTime(nullable: false),
AdminUser_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("Users", t => t.AdminUser_Id)
.Index(t => t.AdminUser_Id);
}
public override void Down()
{
DropIndex("Projects", new[] { "AdminUser_Id" });
DropForeignKey("Projects", "AdminUser_Id", "Users");
DropTable("Projects");
DropTable("Users");
}
}
}
internal sealed class Configuration : DbMigrationsConfiguration<EF_Sample02.Sample2Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
//Database.SetInitializer(new Sample2DbInitializer());
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Sample2Context, Migrations.Configuration>());
<entityFramework>
<contexts>
<context type="EF_Sample02.Sample2Context, EF_Sample02">
<databaseInitializer
type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[EF_Sample02.Sample2Context, EF_Sample02],
[EF_Sample02.Migrations.Configuration, EF_Sample02]], EntityFramework"
/>
</context>
</contexts>
</entityFramework>
CREATE TABLE [dbo].[Projects](
---...
[SomeProp] [nvarchar](max) NULL,
---...
Automatic migration was not applied because it would result in data loss.
internal sealed class Configuration : DbMigrationsConfiguration<EF_Sample02.Sample2Context>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
add-migration Initial -IgnoreChanges
update-database
Update-Database -Verbose
update-database -Script
SELECT * INTO [TempMigrationHistory]
FROM [__MigrationHistory]
DROP TABLE [__MigrationHistory]
EXEC sp_rename [TempMigrationHistory], [__MigrationHistory]
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.IO;
namespace EF_Sample02
{
public class Configuration<T> : DbMigrationsConfiguration<T> where T : DbContext
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
public class SimpleDbMigrations
{
public static void UpdateDatabaseSchema<T>(string SQLScriptPath = "script.sql") where T : DbContext
{
var configuration = new Configuration<T>();
var dbMigrator = new DbMigrator(configuration);
saveToFile(SQLScriptPath, dbMigrator);
dbMigrator.Update();
}
private static void saveToFile(string SQLScriptPath, DbMigrator dbMigrator)
{
if (string.IsNullOrWhiteSpace(SQLScriptPath)) return;
var scriptor = new MigratorScriptingDecorator(dbMigrator);
var script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);
File.WriteAllText(SQLScriptPath, script);
Console.WriteLine(script);
}
}
}
SimpleDbMigrations.UpdateDatabaseSchema<Sample2Context>();
The term 'enable-migrations' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, veri
fy that the path is correct and try again.
At line:1 char:18
+ enable-migrations <<<<
+ CategoryInfo : ObjectNotFound: (enable-migrations:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Test-ModuleManifest : The specified module 'D:\Entity Framework Samples\EF Sample 02\packages\EntityFramework.5.0.0\tools\EntityFramework.psd1' was not loaded because no valid module file was found in any module directory.
At D:\Entity Framework Samples\EF Sample 02\packages\EntityFramework.5.0.0\tools\init.ps1:14 char:34
+ $thisModule = Test-ModuleManifest <<<< (Join-Path $toolsPath $thisModuleManifest)
+ CategoryInfo : ResourceUnavailable: (D:\Entity Framework Samples\E...yFramework.psd1:String) [Test-ModuleManifest], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.TestModuleManifestCommand
Import-Module : Cannot bind argument to parameter 'Name' because it is null.
At D:\Entity Framework Samples\EF Sample 02\packages\EntityFramework.5.0.0\tools\init.ps1:31 char:18
+ Import-Module <<<< $thisModule
+ CategoryInfo : InvalidData: (:) [Import-Module], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ImportModuleCommandThe term 'enable-migrations' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:18
+ enable-migrations <<<<
+ CategoryInfo : ObjectNotFound: (enable-migrations:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundExceptionId Version Description/Release Notes -- ------- ------------------------- EntityFramework 5.0.0 Entity Framework is Microsoft's recommended data access technology for new applications.
about_EntityFramework.help.txt EntityFramework.PowerShell.dll EntityFramework.PowerShell.Utility.dll EntityFramework.PS3.psd1 EntityFramework.psd1 EntityFramework.psm1 init.ps1 install.ps1 migrate.exe Redirect.config Redirect.VS11.config
$psversiontable.psversion
enable-migrations -StartUpProjectName "prj name" -ContextTypeName "ctx name"
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context,Migrations.Configuration>);
internal sealed class Configuration : DbMigrationsConfiguration<GlucosanContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}Database.SetInitializer(new MigrateDatabaseToLatestVersion<GlucosanContext, Migrations.Configuration>());
Update-Database -StartUpProjectName "...name..." -ConnectionString "...data..." -ConnectionProviderName "System.Data.SqlClient"
Cannot open database "Test" requested by the login. The login failed. Login failed for user 'sa'.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<CommonContext, Configuration>());
<add name="TestContext"
connectionString="Data Source=localhost;Initial Catalog=Test;User ID=sa;Password=123;MultipleActiveResultSets=True;"
providerName="System.Data.EntityClient" /> <add name="TestContext"
connectionString="Data Source=localhost;Initial Catalog=Test;Integrated Security=True"
providerName="System.Data.EntityClient" /> The model backing the 'Sample2Context' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Sample2Context, Migrations.Configuration>());
Update-Database -Verbose -ConnectionString "CONNECTIONSTRING" -ConnectionProviderName "System.Data.SqlClient" -StartupProjectName WEBSITE_PROJECT -ProjectName MIGRATION_PROJECT
Update-Database -StartUpProjectName "...name..." -ConnectionString "...data..." -ConnectionProviderName "System.Data.SqlClient"
bool isCompatible = Context.Database.CompatibleWithModel(true);
سلام و باتشکر
من migration را فعال کردم ولی کلاس دوم که حاوی متدهای up ,dwon هست را برام نساخته و زمانی که نوع خاصیت جدولی را تغییر میدم یا جدولی را دستی حذف میکنم پیغام خطای زیر را میبینم برای اینکه این پیغام را نبینم چه کار کنم
There is already an object named 'tablename' in the database.