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.