Entity Framework Core 2 Migration issue - c#

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.

Related

SqlException: Invalid column name, how to fix?

I added two new properties to my model, however when I try to run the project this error appears
How do I fis this?
Here is my model Occorrencias:
public class Ocorrencias
{
[Key]
public int Id { get; set; }
public string NomeFotografia { get; set; }
[ForeignKey("Ignicao")]
[Display(Name = "Ignicao")]
public int IgnicaoFK { get; set; }
public virtual Ignicoes Ignicao { get; set; }
}
The project runs fine but it gives me also an error saying ailed to load resource: the server responded with a status of 500 ()
This is because the properties you added to the Model does not exist in the database.
you can use add-migration to update your database:
open Package Manager Console from Tools>NuGet Package Manage in visual studio and run command below to generate migration file. note that you must replace <MigrationName> with your proper Migration Name.
PM> Add-Migration <MigrationName>
and when the migration file created, use the following command to apply migration to database:
PM> Update-Database
Wait for the Done. to appear.

Use MDF with entityframework Core

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;";

Adding New Table Entity Framwork Code First Approach

That solution does not work in .net core 2 tied to SQL Server 2016. Original Question: Trying to jump into entity framework, using the "Code First Approach". I have my new class setup “NewTable” shown below. I can’t figure out what in the Program Manger Console I need to type to get this table created in my Default Connection String (pointing to a local instance of Sql Server 2016). The database is working and the user in this .net core 2 web app can register his/her name then log in using that new created account. Thanks in advance!!
Default Connection String:
"ConnectionStrings": {
"DefaultConnection" "Server=localhost\RCDSE_Dev;Database=Some Database;User ID=sa;Password=SomePass;"
},
[Table("NewTable")]
public class NewTable
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Database generated key
[Key] //Primary Key
public long Id { get; set; }
[Required]
public string Manager { get; set; }
}
public class NewTableContext : DbContext
{
public DbSet<NewTable> NewTables{ get; set; }
}
Add a constructor to the DbContext as below:
public class NewTableContext : DbContext
{
public DbSet<NewTable> NewTables{ get; set; }
public NewTableContext() : base("DefaultConnection") { }
}
I figured this out. Will post a detailed step by step guide for others in the next couple of days. There are specific things that need to be done in .net core 2 project file that were NOT COVERED in any of the referenced examples by users here. Thanks for all the help..it got me somewhat pointed in a direction, to find the right direction...lol.

Error when creating and connecting to Entity Framework database on an Azure virtual machine

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; }
}

Creating local database with Entity Framework Code First

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.

Categories

Resources