C# 代码先创建表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15747162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Code first create tables
提问by Yustme
I was following thistutorial, and I tried to add a few new columns in the userprofile table. And i tried to create a new table.
我正在关注本教程,并尝试在 userprofile 表中添加一些新列。我试图创建一个新表。
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<TestTabel> TestTabel { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Mobile { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
[Table("TestTabel")]
public class TestTabel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TestId { get; set; }
public string TestName { get; set; }
public string TestMobile { get; set; }
}
Than i tried to update the database with the console with the update-database command, and i got this error msg:
比我尝试使用 update-database 命令使用控制台更新数据库,我收到此错误消息:
There is already an object named 'UserProfile' in the database.
数据库中已经有一个名为“UserProfile”的对象。
The new columns where not added, and neither the table.
未添加的新列,也没有添加表。
What am I missing?
我错过了什么?
[EDIT] I did the add-migration and update-database commands, and this is the out come (had to do the update-database command twice, 2nd time with verbose)
[编辑] 我执行了 add-migration 和 update-database 命令,这是结果(必须执行两次 update-database 命令,第二次使用详细信息)
PM> Add-Migration
cmdlet Add-Migration at command pipeline position 1
Supply values for the following parameters:
Name: test
Scaffolding migration 'test'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration 201304011714212_test' again.
PM> Update-Database
The project 'MVC4SimpleMembershipCodeFirstSeedingEF5' failed to build.
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying code-based migrations: [201304011714212_test].
Applying code-based migration: 201304011714212_test.
Running Seed method.
PM> Update-Database -verbose
Using StartUp project 'MVC4SimpleMembershipCodeFirstSeedingEF5'.
Using NuGet project 'MVC4SimpleMembershipCodeFirstSeedingEF5'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5' (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration).
No pending code-based migrations.
Running Seed method.
PM>
[/EDIT]
[/编辑]
Configuration.cs:
配置.cs:
namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<UsersContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(UsersContext context)
{
WebSecurity.InitializeDatabaseConnection(
"DefaultConnection",
"UserProfile",
"UserId",
"UserName", autoCreateTables: true);
if (!Roles.RoleExists("Administrator"))
Roles.CreateRole("Administrator");
if (!WebSecurity.UserExists("test"))
WebSecurity.CreateUserAndAccount(
"test",
"password",
new { Mobile = "+19725000374", FirstName = "test", LastName = "test" });
if (!Roles.GetRolesForUser("test").Contains("Administrator"))
Roles.AddUsersToRoles(new[] { "test" }, new[] { "Administrator" });
}
}
}
In the Filters folder 1 cs file:
在过滤器文件夹 1 cs 文件中:
namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Filters
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false,
Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
}
Connection string:
连接字符串:
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
Last migration:
上次迁移:
namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class test : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.TestTabel",
c => new
{
TestId = c.Int(nullable: false, identity: true),
TestName = c.String(),
TestMobile = c.String(),
})
.PrimaryKey(t => t.TestId);
}
public override void Down()
{
DropTable("dbo.TestTabel");
}
}
}
采纳答案by NSGaga-mostly-inactive
I'm just going to throw everything in here as a walk-through for getting your code-first and migrations going- attacking various issues that may or may not happen. Note: code-first has proved to be very reliable - and can be worked out with live-scenarios as well - you just need to know what you're doing.
我只是将所有内容都放在此处作为演练,以使您的代码优先和迁移继续进行- 解决可能发生或可能不会发生的各种问题。注意:代码优先已被证明是非常可靠的——并且也可以在实时场景中解决——你只需要知道你在做什么。
Most likely, your migration and the database are basically out-of-sync.
最有可能的是,您的迁移和数据库基本上不同步。
Your existing migration tries to run against the old copy of the database - with ups/downs that were optimized for the 'empty db' I guess.
您现有的迁移尝试针对数据库的旧副本运行 - 我猜有针对“空数据库”优化的起伏。
You need to run your migrations (Add-Migration) against the copy of the Db that you're attaching to - that'll create a 'difference' and just up-to-date your Db (always make sure to backupof course, as it might drop/change etc.).
您需要针对要附加到的 Db 的副本运行迁移(添加迁移) - 这将创建一个“差异”并且只是更新您的 Db(当然始终确保备份,因为它可能会下降/改变等)。
Or if possible, empty your Db - and then start fresh.
或者如果可能的话,清空你的数据库 - 然后重新开始。
Or if live Db - create migrations - and run Update-Database -Script
on your dev-machine - to generate the full Db - or the changes (this is all very rough, you need to adjust to your case). And then apply to your 'live Db' by running scripts.
或者,如果实时数据库 - 创建迁移 - 并Update-Database -Script
在您的开发机器上运行- 以生成完整的数据库 - 或更改(这都非常粗糙,您需要根据您的情况进行调整)。然后通过运行脚本应用到您的“实时数据库”。
You can also check my earlier post on the synchronization...
您还可以查看我之前关于同步的帖子...
MVC3 和 Code First 迁移 - “自创建数据库以来,支持 'blah' 上下文的模型已更改”
EDIT:
Also check this answer AutomaticMigrationsEnabled false or true?
编辑:
还要检查这个答案AutomaticMigrationsEnabled false 还是 true?
And if it's ok with your way of doing things add the AutomaticMigrationsEnabled = true;
to you Configuration
(also under the Migrations folder - created for you)..
如果您的处理方式没问题,请将其添加AutomaticMigrationsEnabled = true;
到您Configuration
(也在 Migrations 文件夹下 - 为您创建)。
Couple steps I always do to clean migrations:
我总是做几个步骤来清理迁移:
(good to backup first)
- Enable-Migrations -force (first-time only - this deletes the configuration.cs and any 'seed'-ing there!)
- AutomaticMigrationsEnabled = true;
- remove existing migrations by hand from project (\Migrations)
- rebuild the project at this point
- Add-Migration Initial
- Update-Database -Force -Verbose
(最好先备份)
- Enable-Migrations -force(仅限第一次 - 这将删除 configuration.cs 和任何“种子”-ing!)
- AutomaticMigrationsEnabled = true;
- 从项目中手动删除现有迁移 (\Migrations)
- 此时重建项目
- Add-Migration Initial
- Update-Database -Force -Verbose
...later on (subsequent migrations):
- Add-Migration SomeOther1
- Update-Database -Force -Verbose
...providing you keep your Db in sync - i.e. careful with 'moving Db around', manually adjusting etc. (and in that case see the other post)
...稍后(后续迁移):
- Add-Migration SomeOther1
- Update-Database -Force -Verbose
...提供您保持数据库同步 - 即小心“移动数据库”,手动调整等(以及在这种情况见另一篇文章)
Couple other things:
其他一些事情:
With PM Console...
- select your project from the list,
- make sure your 'main exe' (calling your data project / assembly - or that same project if console/app) - is set as 'startup' project,
- always watch the console comments - as it may be trying to build and access different project.
使用 PM 控制台...
- 从列表中选择您的项目,
- 确保您的“主 exe”(调用您的数据项目/程序集 - 或者如果控制台/应用程序调用相同的项目) - 设置为“启动”项目,
- 始终观看控制台评论 - 因为它可能正在尝试构建和访问不同的项目。
Connection:
联系:
See this post of mine Migration does not alter my table
In short - your connection is named like your context + your project - if not specified otherwise. It draws from your DbConfig constructor - or app.config (connections). Make sure you're looking at the 'right database' (i.e. what you look through some explorer and what code-first connects to - may be two different things).
请参阅我的这篇文章迁移不会改变我的表格
简而言之 - 您的连接命名为您的上下文 + 您的项目 - 如果没有另外指定。它从您的 DbConfig 构造函数或 app.config(连接)中提取。确保您正在查看“正确的数据库”(即您通过一些资源管理器查看的内容以及代码优先连接的内容 - 可能是两种不同的内容)。
Building:
Make sure your project is set in 'configuration' to build automatically - that can be an issue too.
构建:
确保您的项目在“配置”中设置为自动构建 - 这也可能是一个问题。