gpt4 book ai didi

c# - SQL Server CE Code First 迁移问题

转载 作者:太空狗 更新时间:2023-10-29 20:27:54 25 4
gpt4 key购买 nike

我在尝试为我的桌面 .NET 应用程序启用(代码优先)迁移我的 SQL Server Compact 4.0 数据库时遇到了很多问题。

Enable-Migrations 确实有效,目录 Migrations 已创建。之后,当我尝试运行 Add-Migration InitialMigration 时,我得到:

Access to the database file is not allowed. [ 1914,File name = Logo.sdf,SeCreateFile ]

这是第一个问题,但我通过以管理员身份运行 Visual Studio 解决了它...不喜欢该解决方案,也不知道在以后的生产中它是否可以在没有以管理员模式运行应用程序的情况下工作。我暂时把这个问题放在一边......

我的连接字符串:

<add name="LogoContext" 
connectionString="Data Source=Logo.sdf"
providerName="System.Data.SqlServerCE.4.0"/>`

因此,在管理员模式下运行 Add-Migration InitialMigration 后,我得到一个空的迁移...没关系。然后我删除迁移并添加一个新类:

using System;
using System.Collections.Generic;

public class Blog
{
public int ID { get; set; }
public string Title { get; set; }
}

我添加对上下文类的引用:

public class LogoContext : DbContext
{
public DbSet<Word> Words { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Blog> Blogs { get; set; }
}

然后再次运行Add-Migration InitialMigration得到:

public partial class InitialMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Blogs",
c => new
{
ID = c.Int(nullable: false, identity: true),
Content = c.String(maxLength: 4000),
})
.PrimaryKey(t => t.ID);
}

public override void Down()
{
DropTable("dbo.Blogs");
}
}

运行 Update-Database 后,我看到:

Applying code-based migrations: [201304211225255_InitialMigration].
Applying code-based migration: 201304211225255_InitialMigration.
Running Seed method.

现在问题出现了 - 在我的服务器资源管理器中,我检查了数据库 Logo.sdf,它包含表 Blogs!我什至尝试从我的应用程序运行这段代码:

var db = new LogoContext();
db.Posts.Add(new Blog { Title= "moo" });
db.SaveChanges();

检查我的 Server Explorer 是否没有显示表格..但我得到一个异常:

The specified table does not exist. [ Blogs ]

所以迁移显然没有应用到我的 Logo.sdf 文件 :(

如果我从 app.config 中删除连接字符串,则假定连接到 SQL Server Express 的本地实例。在那里它完美地工作!当我使用 SQL Server Management Studio 检查数据库时,我看到了新的 Blogs 表以及有关迁移的元数据的系统表...

另一个小信息:

当我尝试再次运行 Update-Database 时,我收到“没有挂起的基于代码的迁移”。这告诉我一些数据毕竟被保存到 Logo.sdf 中......至少有一些关于迁移的元数据,但我仍然无法在服务器资源管理器中看到该表。

我正在使用 VS 2012 和 EF 5.0。

请帮助我理解这一点...在我看来,有些事情是严重错误的,因为它只适用于 SQL Server Express 实例,但不适用于 SQL Server CE 4.0。 :((

谢谢!大卫

最佳答案

所以问题是解决方案在这里创建了一个单独的 .sdf 文件:

"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Logo.sdf"

恕我直言,这是出乎意料和奇怪的...

我最终使用了这个连接字符串:

<add name="LogoContext" connectionString="Data Source=|DataDirectory|\Logo.sdf" providerName="System.Data.SqlServerCE.4.0"/>

这引用了 bin/Debug/Logo.sdf,它在开发期间和单独运行 .exe 时有效。

这种方式的唯一问题是我的 Logo.sdf 项目文件(“如果更新”被复制到 Debug)现在被完全忽略了。所有迁移都将在调试文件上运行。这可能也不错......

感谢 Erik 的提示!大卫

关于c# - SQL Server CE Code First 迁移问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com