使用实体框架,CREATE DATABASE失败:系统找不到指定的文件

时间:2015-05-28 14:59:15

标签: c# sql-server entity-framework localdb

我收到此错误:

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Directory lookup for the file "C:\pub\LSK\Dev\src\LSK.Services\LSK.Services\App_Data\LSK.Packets.mdf" failed with the operating system error 2(The system can not find the specified file).

CREATE DATABASE failed. Some file names listed could not be created. Check related errors.



using (var context = new LDTContext())
            {
                context.Packets.AddRange(packets); // Here occurs the exception
                context.SaveChanges();
            }


public class LDTContext : DbContext
    {
        public LDTContext()
            : base("name=LDTContext")
        {
            Configuration.LazyLoadingEnabled = true;
            Configuration.ProxyCreationEnabled = true;
            Configuration.ValidateOnSaveEnabled = true;
            Configuration.AutoDetectChangesEnabled = true;
            Configuration.UseDatabaseNullSemantics = false;
        }


        public DbSet<Packets> Packets{ get; set; }

    }

在我的app.config中:

<add name="LDTContext" connectionString="Server=(LocalDb)\LSK;Initial Catalog=LSK.Packets;Integrated Security=true;AttachDBFilename=|DataDirectory|\LSK.Packets.mdf"  providerName="System.Data.SqlClient" />

为什么在将数据推入表中时,第一个AddRange()上没有创建数据库?

1 个答案:

答案 0 :(得分:0)

您的连接字符串错误[Data Source =(LocalDb)\ v11.0 not Server =(LocalDb)\ LSK]。试试

connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\LSK.Packets.mdf;Initial Catalog=LSK.Packets;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"

http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string