1

我正在尝试在 MVC 项目中创建数据库。代码优先方法。我写了我的模型和一个DbContext数据库。我无法连接到数据库。我怀疑问题出在我的连接字符串中,但我不确定。我想要的数据库将包含两个表,定义如下:

public class EmployeeRequest
{
    [Key]
    public int EmployeeRequestId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public int ExtNumber { get; set; }
    public bool isProcessed { get; set; }
    public virtual ICollection<ChangeOrder> ChangeOrders { get; set; }
}

public class ChangeOrder
{
    [Key]
    public int ChangeOrderId { get; set; }
    public short Operation { get; set; } //0 - Add, 1- delete
    public int TargetExt { get; set; }
    public short Status { get; set; } //0- Pending, 1- Approved, 2- Denied
    public DateTime DtRequested { get; set; }
    public DateTime DtProcessed { get; set; }
    public DateTime DtChangesApplied { get; set; }
    public int EmployeeRequestID { get; set; }
    public virtual EmployeeRequest Request { get; set; }
 }

DbContext课程是:

public class RequestsContext : DbContext
{
    public DbSet<EmployeeRequest> EmployeeRequests { get; set; }
    public DbSet<ChangeOrder> ChangeOrders { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

连接字符串:

<add name="RequestsContext" 
     providerName="System.Data.SqlClient" 
     connectionString="Data Source=(LocalDb);Database=Requests.mdf;Trusted_Connection=True"/>

我得到的错误是无法与主机建立连接。

我不确定为什么会这样。有任何想法吗?

4

2 回答 2

1

将连接字符串提供给 DbContext 基础。

public class RequestsContext : DbContext
{
    public DbSet<EmployeeRequest> EmployeeRequests { get; set; }
    public DbSet<ChangeOrder> ChangeOrders { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

    public RequestsContext ()
    : base("RequestsContext")
    {}

}
于 2013-07-29T20:54:17.007 回答
1

请检查应用程序是否有权访问 .mdf 文件位置。如果您的应用程序位于“myDocuments”等类型的文件夹中,则默认情况下应用程序可能无法访问它。

于 2013-07-29T20:55:05.547 回答