我正在尝试在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"/>
我得到的错误表明无法与主机建立连接。
我也不确定为什么会这样。有任何想法吗?
答案 0 :(得分: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")
{}
}
答案 1 :(得分:1)
请检查应用程序是否有权访问.mdf文件位置。如果您的应用程序驻留在“myDocuments”等类型的文件夹中,则默认情况下应用程序可能无法访问它。