当我运行我的uwp项目时,SqlException generetad

问题描述 投票:-1回答:2

我创建了一个uwp项目和一个.NET Standard项目。 .NETproject是我的DB的创建者,codeFirst里面有我的模型和我的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和initialize方法

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)

谢谢你的帮助

c# uwp code-first sqlexception ef-core-2.1
2个回答
0
投票

您的ConnectionString不正确,请使用visual studio检查您的Connection

enter image description here

enter image description here

enter image description here


0
投票

请检查您的uwp应用程序的功能,如果已激活。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.