I have problem with creating local db with EF code first. When I try create db with command update-database Visual Studio returns the error:
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: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
In earlier project I haven't any problem with do that.
Context Class
public class Context : DbContext {
public DbSet<Project> Projects { get; set; }
public DbSet<Task> Tasks { get; set; }
public DbSet<Team> Teams { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Ignore<IIdentifableEntity>();
modelBuilder.Entity<Project>().HasKey(p => p.Id).Ignore(p => p.EntityId);
modelBuilder.Entity<Task>().HasKey(t => t.Id).Ignore(t => t.EntityId);
modelBuilder.Entity<Team>().HasKey(t => t.Id).Ignore(t => t.EntityId);
modelBuilder.Entity<User>().HasKey(u => u.Id).Ignore(u => u.EntityId);
}
}
App.config
Thank you for any help.
Make sure your connection string is valid and working with the reference database associated with respective username and password.
You can check your database is connecting using SQL server management studio.
Related
I'm trying to figure out how to connect to an .mdf file using entityframework core. I found a resource on how to connect to one here However it doesn't seem to be working. I've made a var simple context using the Northwind dataset
public class Order
{
public int OrderId { get; set; }
public string CustomerID { get; set; }
public int EmployeeID { get; set; }
public DateTime OrderDate { get; set; }
// etc.
}
public class NorthwindContext : DbContext
{
public NorthwindContext(DbContextOptions options) : base(options) { }
public DbSet<Order> Orders { get; set; }
}
I've created a test class to attempt to connect to the DB
public string NorthwindConnectionString = #"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\source\Astoot\RestEzCore.Tests\TestDB\NORTHWND.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
[TestMethod]
public void TestMethod1()
{
var optionsBuilder = new DbContextOptionsBuilder<NorthwindContext>();
//I've also tried UseSqlLite()
optionsBuilder.UseSqlServer(this.NorthwindConnectionString);
using (var context = new NorthwindContext(optionsBuilder.Options))
{
var orders = context.Orders.ToList();
Assert.IsTrue(orders.Any());
}
}
However when I attempt to run my tests I get an error
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
Edit
I've also tried moving my MDF to users folder and connect using this connection string:
Data Source=(LocalDB)\MSSQLLocalDB;DataBase=Northwind;Integrated Security=True;Connect Timeout=30"
However this doesn't seem to work as well, it throws an exception
SqlException: Cannot open database "Northwind" requested by the login. The login failed.
Login failed for user 'MyUser'
Is there something wrong with my connection string?
I can't quite seem to figure out how to use an MDF with entityframework
I did some investigation, and it turns out that it was returning a bogus error because Northwind DB in built from SQL Server 2000, and I'm running SQL server 2016 so Instead I Created a Sample DB and used that as an MDF.
Now my connection string looks like so:
public static string MDF_Directory
{
get
{
var directoryPath = AppDomain.CurrentDomain.BaseDirectory;
return Path.GetFullPath(Path.Combine(directoryPath, "..//..//..//TestDB"));
}
}
public string astootConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB; " +
"AttachDbFilename="+ MDF_Directory + "\\Astoot.mdf;" +
" Integrated Security=True; Connect Timeout=30;";
I am building app using ASP.NET Core 2 and DB part is EF core 2.
i have model like this
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
This is context file
public class EFCoreDbContext:DbContext
{
public EFCoreDbContext(DbContextOptions<EFCoreDbContext> options)
: base(options)
{
}
public DbSet<ChatMessage> ChatMessages { get; set; }
}
and finally startup.cs
services.AddDbContext<EFCoreDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MooltiRoomDatabase")));
And connection string in appsettings.json
"ConnectionStrings": {
"MooltiRoomDatabase": "Server=DESKTOP-BCQ6IAU\\CHATDB,Database=MultiRoomChat;Trusted_Connection=True;"
}
Through package manager console i was runing Add-Migration the command completed successfully despite the fact that in DB it did not create corresponding table,after that i've read that i need to run Update-Database command for creating table and when i run this command, i got a error like this
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: SQL
Network Interfaces, error: 25 - Connection string is not valid)
As you can see in the error message, 'Connection string is not valid.' You used "," instead of ";" before the Database.
So now you have:
"Server=DESKTOP-BCQ6IAU\\CHATDB,Database=MultiRoomChat;Trusted_Connection=True;"
But, you should use this:
"Server=DESKTOP-BCQ6IAU\\CHATDB;Database=MultiRoomChat;Trusted_Connection=True;"
In ASP Net Core there is also a development configuration that gets used. You should notice an icon next to app settings - the "drop down" icon. See if adding your connection string to the development config helps.
Also the way the app settings get accessed has changed so make sure you are writing the correct code to receive the value.
I want to create database if its not exist. I am using sqlite as a database source and Entity Framework. At first I added new model (code first) and set database source as database.db in current directory.
Next, I've added simple class:
class User {
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
And of course database context:
class TestContext : DbContext {
public DbSet<User> Users { get; set; }
public TestContext() :base("TestModel"){
//Create database always, even If exists
Database.SetInitializer<TestContext>(new DropCreateDatabaseAlways<TestContext>());
}
}
I've already had connectionString in app.config:
<connectionStrings>
<add name="TestModel" connectionString="data source="C:\Users\root\Documents\Visual Studio 2015\Projects\dbTEST\dbTEST\bin\Debug\database.db"" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
And for some reason after running this piece of code:
using (var ctx = new TextContext()) {
ctx.Database.Create();
}
I am getting error:
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
Additional information: Database 'main' cannot be created because it already exists.
I cant understand what's wrong with this. I dont know where main database comes from. I set database file as database.db. Can you help me with that?
Your constructor dictates that the DB will be dropped and created each time the application starts.
Therefore remove ctx.Database.Create() as this is handled by the framework.
I created an virtual machine on Azure with VS2017 installed on it. Then, I tried to clone a project I'm working on that works on adding elements to a database using Entity Framework code-first.
But I get this error when trying to run the project:
Unhandled Exception: System.Data.SqlClient.SqlException: 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Any idea how to resolve this?
(N.B. the project is working fine on my local machine)
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
If your SQL Server instance is hosted on your local network, please make sure whether it has been configured that it can be remote access. If it can't be remote access, I am afraid you need to migrate your SQL Server database to your Virtual Machine or Azure SQL. Then you could modify your connection string to access the new database which can be accessed from your project.
I don't want to migrate anything, I want to make a new database on the VM..
You could use Local DB which works on your VM. If your application type is web application, you could modify your database as following. EF will create a new database in your App_Data folder.
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True
Otherwise, you need to put the detail configure the detail path of your database file in the connection string. For example,
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Database1.mdf;Integrated Security=True
I just tested the LocalDB on Azure Windows 10 virtual machine with VS 2017 installed and it can create database when I use EF code first. Following is my test code.
class Program
{
static void Main(string[] args)
{
using (SchoolContext context = new SchoolContext())
{
context.Students.Add(new Student { ID = 1, FirstMidName = "FMN", LastName = "LN", EnrollmentDate = DateTime.Now });
context.SaveChanges();
}
Console.Write("Create database OK");
Console.Read();
}
}
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
public class SchoolContext : DbContext
{
public SchoolContext() : base(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\amor\Desktop\TestEF\CodeFirstSample\Database1.mdf;Integrated Security=True")
{
}
public DbSet<Student> Students { get; set; }
}
I'm developing a project and I made changes to my models, and now whenever I run my project I get these errors for all the model that I made changes to:
for my person model:
Invalid column name 'Location'.
Invalid column name 'EmailAddress'.
Invalid column name 'PlaceOfBirth'.
for my guardian model:
Invalid object name 'Admission.Guardian'.
Here is my DbContext model:
public class SchoolInfoEntities: DbContext
{
public DbSet<Students> Student { get; set; }
public DbSet<Class> Classes { get; set; }
public DbSet<Guardian> Guardians { get; set; }
public DbSet<Staff> Staffs { get; set; }
public DbSet<Subject> Subjects { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<SchoolDetails> SchoolDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Students>()
.HasMany(t => t.Guardians)
.WithMany(t => t.Students)
.Map(m =>
{
m.ToTable("Admission.StudentGuardian");
m.MapLeftKey("StudentId");
m.MapRightKey("GuardianId");
});
modelBuilder.Entity<Staff>()
.HasMany(t => t.Subjects)
.WithMany(t => t.Staffs)
.Map(m =>
{
m.ToTable("Admission.SubjectInstructor");
m.MapLeftKey("StaffId");
m.MapRightKey("SubjectName");
});
modelBuilder.Entity<Staff>()
.HasMany(t => t.Departments)
.WithMany(t => t.Staffs)
.Map(m =>
{
m.ToTable("Admission.StaffDepartment");
m.MapLeftKey("StaffId");
m.MapRightKey("DepartmentId");
});
Database.SetInitializer<SchoolInfoEntities>(null);
}
}
Is there anything that I'm not considering? Please help me guys.
You can't change the model fields without updating the related database fields. You need to create a migration and apply it in order to keep your models in sync with the database schema.
https://docs.asp.net/en/latest/data/ef-mvc/migrations.html
If you have a production version of the database you'll need to run the same migrations on it.
You need to run below commands on the Package Manger console before run your app.
Note : you need to set correct connection string where the place (db server) you need to run the scripts.
PM> Add-Migration "Added_New_Properties"
PM> Update-Database
Since you are using Code First, EntityFramework always make sure that the model is synchronized with the database, when the application starts, it compares the classes and its properties with the tables and columns in the database taking into consideration any changes you made using the Fluent API inside your Context.
When you add a new property into any class, you have to either add a corresponding column in the database table that maps to this class, or you can let EntityFramework do it for you by using Migration.
You have to enbale migration first using the Enable-Migrations command
After that, run the command Add-Migration [Migration Name] which will compare the model to the database and generate some code inside the Migrations folder to update the database, it should have an Up and Down methods.
To run the Up method which updates the database to the code, you have to run the Update-Database command.
All of these commands must run inside the Package Manager Console which you can reach from Tools -> NuGet Package Manager -> Package Manager Console.