August 9, 2021 07:52 by
Peter
Add package by right clicking on the project. Click on manage nuget packages, browse package, search microsoft.entityframeworkcore.sqlserver , install it, search microsoft.entityframeworkcore.tool,microsoft.visualstudio.web.codegenerator.design , click ok and click accept on pop up.
This package will be added in packages. Add DataBaseContext.cs class in model inherit DbContext in the method class of DataBaseContext and use namespace. Microsoft.EntityFrameworkCore forDbContext Definition makes a constructor for connectivity with the database.
public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options)
{
}
In database context class add a class in the model for the table you want to make in the database. You can use a prop and double tab. For auto creating a property in class assign primary key here only on the property of class as an attribute with keyword [Key]. Use namespace System.ComponentModel.DataAnnotations for key attribute definition now link this table as DbSet type of property in DataBaseContext class LIKE this,
public DbSet<Student> students { get; set; }
Now use connection string in appsetting.json below "AllowedHosts": "*",
"ConnectionStrings": {
"DatabaseConnection": "Data Source=DESKTOP-DCDA4OG\\SQLEXPRESS; Initial Catalog=CodeFirst; Integrated Security=True;"
}
Now create a new database in SQL server rest of table will automatically be created by the project itself
add,
string connection = Configuration.GetConnectionString("DataBaseConnection");
services.AddDbContext<DataBaseContext>(options => options.UseSqlServer(connection));
in Configuresrevices in startup.cs use namespace microsoft.entityframeworkcore for usesqlserver connectivity keyword now add controller lets say with name usercontroller add model class add datacontext class click add you can auto create add update delete list by scaffolding now do migration,
select tools - > nugetpackage manager -> package manager console
write Add-Migration InitialCreate and enter
Write update-database enter
Now run controllers.
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.