尝试使用代码第一个Entity Framework创建localdb时抛出异常

时间:2015-08-02 20:53:13

标签: c# wpf entity-framework

我尝试使用代码优先方法在Entity Framework中创建一个全新的数据库来测试我的WPF Prism应用程序。每当应用程序启动时,都应该创建一个新的数据库,因为这是一个在开发过程中会快速变化的新项目。

尝试创建数据库时,我遇到了以下异常:

  

"无法创建文件' C:\ Users \ Edvard \ SharedResources.DataAccess.EFDbContext.mdf'因为它已经存在更改文件路径或文件名,然后重试该操作。\ r \ nCREATE DATABASE失败。无法创建列出的某些文件名。检查相关错误。"} System.Exception {System.Data.SqlClient.SqlException}

这就是datacontext构造函数的样子:

public EFDbContext()
{
    Database.SetInitializer<EFDbContext>(new CustomInitializer<EFDbContext>());
}

正如您在上面所看到的,我正在调用自定义初始化程序,以便我可以使用信息为数据库设定种子:

public class CustomInitializer<T> : DropCreateDatabaseAlways<EFDbContext>
{
    protected override void Seed(EFDbContext context)
    {
        context.Users.Add(new User
        {
            SaveableClaims = new List<SaveableClaim>
            {
                new SaveableClaim { Type = CustomClaimTypes.Username, Value = "Mark" },
                new SaveableClaim { Type = CustomClaimTypes.HashedPassword, Value = "MB5PYIsbI2YzCUe34Q5ZU2VferIoI4Ttd+ydolWV0OE=" },
                new SaveableClaim { Type = CustomClaimTypes.FirstName, Value = "Mark" },
                new SaveableClaim { Type = CustomClaimTypes.LastName, Value = "Johnson" },

                new SaveableClaim { Type = CustomClaimTypes.UIAccess, Value = UIAccessTypes.SearchMenuRead }
            }
        });

        context.Users.Add(new User
        {
            SaveableClaims = new List<SaveableClaim>
            {
                new SaveableClaim { Type = CustomClaimTypes.Username, Value = "John" },
                new SaveableClaim { Type = CustomClaimTypes.HashedPassword, Value = "hMaLizwzOQ5LeOnMuj+C6W75Zl5CXXYbwDSHWW9ZOXc=" },
                new SaveableClaim { Type = CustomClaimTypes.FirstName, Value = "John" },
                new SaveableClaim { Type = CustomClaimTypes.LastName, Value = "Markson" }
            }
        });

        base.Seed(context);
    }
}

我在上面的代码中做错了什么可能导致这个?为了提供一些额外的细节,我使用了localdb。这是App.config文件:

<configSections>
  <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="v11.0" />
    </parameters>
  </defaultConnectionFactory>
</entityFramework>

如果我能提供更多信息,请告诉我。感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:2)

找到位于以下位置的文件:

  

&#39; C:\用户\爱德华\ SharedResources.DataAccess.EFDbContext.mdf&#39;

删除它。