【发布时间】:2023-03-05 19:18:01
【问题描述】:
我首先在我的应用程序中使用实体框架代码。如果我在第一台机器上创建数据库,然后将我的项目与数据库(.mdf 和 .ldf 文件)一起使用并尝试在其他机器上克隆这个项目,但是当我运行这个项目时它无法打开数据库(权限错误) .
是否可以使用某些用户在实体框架数据库中创建或在没有授权许可的情况下创建数据库?
你可以举一些连接字符串或 DbContextConfiguration 的例子吗?
这是我的例外:
无法创建文件 'D:\nullam\Nullam.WebUI\App_Data\Nullam.DataLayer.NullamDbContext.mdf' 因为它已经存在。更改文件路径或文件名,以及 重试操作。创建数据库失败。列出了一些文件名 无法创建。检查相关错误。
Global.asax
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Nullam.DataLayer;
namespace Nullam.WebUI
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NullamDbContext>());
}
}
}
NullamDbContext.cs
using Nullam.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nullam.DataLayer
{
public class NullamDbContext : DbContext
{
public NullamDbContext() : base("NullamDb")
{
}
public DbSet<Member> Members { get; set; }
public DbSet<SocialEvent> SocialEvents { get; set; }
}
}
Configuration.cs
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nullam.DataLayer.Migrations
{
class Configuration : DbMigrationsConfiguration<NullamDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(NullamDbContext 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" }
// );
//
}
}
}
Web.config
<connectionStrings>
<add name="NullamDb"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Nullam.DataLayer.NullamDbContext.mdf;Integrated Security=SSPI;"/>
</connectionStrings>
【问题讨论】:
-
错误是什么?你能分享你提到的相同项目的代码吗?
-
@Sampath 我在我的问题中添加了代码。另外我想注意我没有改变模型和数据库不能下降。我尝试通过连接exploner ant连接到数据库,但它不允许我。例外:无法打开登录请求的数据库“Nullam.DataLayer.NullamDbContext”。登录失败。我使用Windows身份验证。如果您需要更多代码,我将再次编辑我的问题。谢谢。
-
尝试以管理员权限启动 Visual Studio
-
类似于@swissben 的回答,在新机器上,尝试使用管理员启动IIS 应用程序池,并将模拟用户添加到管理员组。
标签: c# entity-framework