Wednesday, 29 December 2021

Asp.Net Core 6: Connect To Sql Server Database With Entity Framework Using C#

12/29/2021 - By Pranav Singh 0

In this article I will show you how you can connect to a MS  Sql server database and get the data stored in an object table in your asp.net core 6 web application. First we will create a new database in ms sql server and in this we will create a new table with some data.


SQL  server table C#

After creating this we will create a new asp.net core 6 project. In this we will add SQL server provider and Entity tool package. Please check the below packages.

 

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

 

OR 


https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/5.0.13

https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tools/5.0.13

 

We need to install the package from package manager.

Entityframework package manager


After installing the above packages we will get it in solution explorer.


Entityframework package manager

Here for making connection with database by using entity framework we will run the Scaffold-DbContext. Please check the below command.


Scaffold-DbContext "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DataDB

 

In above command we have given sql server connection string and then the provide name and output folder name. Here Output folder name is the folder name where we after execution of command all the DB entity object partial class with DBcontext file will be created.  This approach is called DB first approach.


entity object in .net core


Here we will check the entity object detail of employee.


using System;

using System.Collections.Generic;

namespace TestProject.DataDB

{

    public partial class Employee

    {

        public int Id { get; set; }

        public string EmployeeName { get; set; }

        public string Designation { get; set; }

        public string Department { get; set; }

        public int? Salery { get; set; }

    }

} 


Here you can see the class property of employee is same as the fields we have defined in the SQL table.

Now we will will check the DB context file. In this file we will get the connection string and all the table object details.


using System;

using Microsoft.EntityFrameworkCore;

using Microsoft.EntityFrameworkCore.Metadata;

namespace TestProject.DataDB

{

    public partial class TestDBContext : DbContext

    {

        public TestDBContext()

        {

        } 

        public TestDBContext(DbContextOptions<TestDBContext> options)            : base(options)

        {

        } 

        public virtual DbSet<Employee> Employees { get; set; } 

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

        {

            if (!optionsBuilder.IsConfigured)

            {

                optionsBuilder.UseSqlServer("ServerLAPTOP-DCE5GAKD\\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;");

            }

        } 

        protected override void OnModelCreating(ModelBuilder modelBuilder)

        {

            modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS"); 

            modelBuilder.Entity<Employee>(entity =>

            {

                entity.ToTable("Employee"); 

                entity.Property(e => e.Department)

                    .HasMaxLength(50)

                    .IsUnicode(false); 

                entity.Property(e => e.Designation)

                    .HasMaxLength(50)

                    .IsUnicode(false); 

                entity.Property(e => e.EmployeeName)

                    .HasMaxLength(50)

                    .IsUnicode(false);

            });

            OnModelCreatingPartial(modelBuilder);

        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

    }

} 

 

Above is the autogenerated file. In this check the highlighted part of the code. This the connection string.  Now add a controller and put the below ode to check the connection. In this we will access all the data present in the table.


TestDBContext testDBContext = new TestDBContext();

var empdata = testDBContext.Employees;

 

Now lets check the output.


Asp.Net Core 6: Connect To Sql Server Databasen With Entity Framework Usingn C#

Subscribe My YouTube Chanel


Download

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top