ConnectWithSqlLiteDatabase in Asp.Net Core
Package
- "Microsoft.EntityFrameworkCore" Version="5.0.0"
- "Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0"
- "Microsoft.EntityFrameworkCore.Tools" Version="5.0.0"
- "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2"
Data[Folder]
DataContext.cs
using ConnectWithSqlLiteDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConnectWithSqlLiteDatabase.Data
{
public class DataContext : DbContext
{
//short cut to generate constructor ctur+tab+tab
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
}
}
Models[Folder]
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConnectWithSqlLiteDatabase.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "DataSource=Student.DB"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Startup.cs
using ConnectWithSqlLiteDatabase.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConnectWithSqlLiteDatabase
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<DataContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
0 Comments