我创建了一个uwp项目和一个.NET Standard项目。 .NETproject是使用代码首先创建数据库的创建者,首先是模型和DBContext
我的模特
public class Department
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string DepartmentDescription { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }
[Required]
[MaxLength(50)]
public string EmployeeName { get; set; }
public int DepartmentId { get; set; }
public int Salary { get; set; }
[ForeignKey("DepartmentId")]
public virtual Department Department { get; set; }
}
DBContext和初始化方法
public class EmployeeContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)
{
Database.Migrate();
}
}
public class Initialize
{
public static EmployeeContext GetContext()
{
var connectionString = @"Server=localhost;Database=EFCoreTest;Trusted_Connection=True;";
DbContextOptionsBuilder<EmployeeContext> options = new DbContextOptionsBuilder<EmployeeContext>();
options.UseSqlServer(connectionString);
return new EmployeeContext(options.Options);
}
}
在UWP中(在app.xaml.cs中),我第一次调用我的DBContext创建我的数据库,但这生成了SqlException
我的app.xaml.cs上的通话
var context = Initialize.GetContext();
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)
感谢您的帮助