To connect your ASP.NET Core code to a Microsoft SQL Server database, you will need to follow these steps:
- Install the necessary NuGet packages:
Install the
Microsoft.EntityFrameworkCore.SqlServer
package, which includes the Entity Framework Core provider for Microsoft SQL Server.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
- Create a connection string: Create a connection string that specifies the server name, database name, and any necessary authentication information. The connection string should be in the following format:
"Server=server_name;Database=database_name;User Id=user_id;Password=password;"
- Configure the DbContext:
In your DbContext class, override the
OnConfiguring
method and use theUseSqlServer
extension method to specify the connection string and any other options. For example:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=server_name;Database=database_name;User Id=user_id;Password=password;");
}
Create your entity classes:
Create POCO (plain old CLR object) classes to represent the entities in your database. These classes should be decorated with the[Table]
attribute and the properties should be decorated with the[Column]
attribute.Create a
DbSet
for each entity:
In yourDbContext
class, create aDbSet
property for each entity in your model. For example:
public DbSet<Product> Products { get; set; }
- Run migrations:
Use the
Add-Migration
andUpdate-Database
commands in the Package Manager Console to apply your entity model to the database.
dotnet ef migrations add InitialCreate
dotnet ef database update
- Use LINQ to query the database:
In your code, use LINQ queries to retrieve and manipulate data from the database. You can use the
DbSet
properties to access the entities in your model.
Thanks for reading...
Happy Coding!
Top comments (2)
Personally I do not recommend Entity Framework for web development. I have several reasons, some of them explained here. Nowadays I can enumerate a few performance reasons why EF is no good.
Instead I encourage any new developer to use Dapper.
Alright bro.
I will check it out.
But, I don't accept the idea of making people feel a tool is not good. EF as it pro and con, likewise Dapper. It's now left to the developer on which to choose.