首页 > 数据库 >dotnet 连接sqlite数据库 orm EntityFrameworkCore

dotnet 连接sqlite数据库 orm EntityFrameworkCore

时间:2023-07-15 21:13:11浏览次数:44  
标签:sqlite id EntityFrameworkCore orm learn dotnet Pizzas public pizza

dotnet_learn/appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

dotnet_learn/appsettings.Development.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

dotnet_learn/dotnet_learn.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.9" />
    <PackageReference Include="Microsoft.Data.Sqlite" Version="7.0.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.4" />
  </ItemGroup>

</Project>

dotnet_learn/Program.cs

using Microsoft.EntityFrameworkCore;
using dotnet_learn.Models;

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Pizzas") ?? "Data Source=Pizzas.db";

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// 使用内存数据库
// builder.Services.AddDbContext<PizzaDb>(options => options.UseInMemoryDatabase("items"));
// 使用sqlite数据库
builder.Services.AddSqlite<PizzaDb>(connectionString);
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.MapGet("/newpizzas", async (PizzaDb db) => await db.Pizzas.ToListAsync());
app.MapPost("/newpizza", async (PizzaDb db, Pizza pizza) =>
{
    await db.Pizzas.AddAsync(pizza);
    await db.SaveChangesAsync();
    return Results.Created($"/newpizza/{pizza.Id}", pizza);
});


app.Run();

dotnet_learn/models/Pizza.cs

using Microsoft.EntityFrameworkCore;
namespace dotnet_learn.Models;

public class Pizza
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public bool IsGlutenFree { get; set; }

}
class PizzaDb : DbContext
{
    public PizzaDb(DbContextOptions options) : base(options) { }
    public DbSet<Pizza> Pizzas { get; set; } = null!;
}

dotnet_learn/Controllers/PizzaController.cs

using dotnet_learn.Models;
using dotnet_learn.Services;

using Microsoft.AspNetCore.Mvc;

namespace ContosoPizza.Controllers;

[ApiController]
[Route("[controller]")]
public class PizzaController : ControllerBase
{
    public PizzaController()
    {
    }

    // GET all action
    [HttpGet]
    public ActionResult<List<Pizza>> GetAll() =>
        PizzaService.GetAll();

    // GET by Id action
    [HttpGet("{id}")]
    public ActionResult<Pizza> Get(int id)
    {
        var pizza = PizzaService.Get(id);

        if (pizza == null)
            return NotFound();

        return pizza;
    }

    // POST action
    [HttpPost]
    public IActionResult Create(Pizza pizza)
    {
        PizzaService.Add(pizza);
        return CreatedAtAction(nameof(Get), new { id = pizza.Id }, pizza);
    }


    // PUT action
    [HttpPut("{id}")]
    public IActionResult Update(int id, Pizza pizza)
    {
        if (id != pizza.Id)
            return BadRequest();

        var existingPizza = PizzaService.Get(id);
        if (existingPizza is null)
            return NotFound();

        PizzaService.Update(pizza);

        return NoContent();
    }

    // DELETE action
    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var pizza = PizzaService.Get(id);

        if (pizza is null)
            return NotFound();

        PizzaService.Delete(id);

        return NoContent();
    }
}

dotnet_learn/Services/PizzaService.cs

using dotnet_learn.Models;

namespace dotnet_learn.Services;

public static class PizzaService
{
    static List<Pizza> Pizzas { get; }
    static int nextId = 3;
    static PizzaService()
    {
        Pizzas = new List<Pizza>
        {
            new Pizza { Id = 1, Name = "Classic Italian", IsGlutenFree = false },
            new Pizza { Id = 2, Name = "Veggie", IsGlutenFree = true }
        };
    }

    public static List<Pizza> GetAll() => Pizzas;

    public static Pizza? Get(int id) => Pizzas.FirstOrDefault(p => p.Id == id);

    public static void Add(Pizza pizza)
    {
        pizza.Id = nextId++;
        Pizzas.Add(pizza);
    }

    public static void Delete(int id)
    {
        var pizza = Get(id);
        if (pizza is null)
            return;

        Pizzas.Remove(pizza);
    }

    public static void Update(Pizza pizza)
    {
        var index = Pizzas.FindIndex(p => p.Id == pizza.Id);
        if (index == -1)
            return;

        Pizzas[index] = pizza;
    }
}

标签:sqlite,id,EntityFrameworkCore,orm,learn,dotnet,Pizzas,public,pizza
From: https://www.cnblogs.com/zhuoss/p/17556954.html

相关文章

  • Transform LiveData
    查询资料的其中一个场景:创建一个回调函数,当查询后台的时候,后台有结果了,回调对应的回调函数,并将结果保存到LiveData中。publicclassDataModel{    ...    publicMutableLiveData<List<Repo>>searchRepo(Stringquery){        finalMutableLiveData<......
  • [论文速览] A Closer Look at Self-supervised Lightweight Vision Transformers
    Pretitle:ACloserLookatSelf-supervisedLightweightVisionTransformersaccepted:ICML2023paper:https://arxiv.org/abs/2205.14443code:https://github.com/wangsr126/mae-literef:https://mp.weixin.qq.com/s/7FiDLYBZiAX-xkW-dZBU9Q关键词:lightweght,ViT......
  • 论文日记四:Transformer(论文解读+NLP、CV项目实战)
    导读重磅模型transformer,在2017年发布,但就今天来说产生的影响在各个领域包括NLP、CV这些都是巨大的!Paper《AttentionIsAllYouNeed》,作者是在机器翻译这个领域进行的实验,当然我们今天知道它被应用到了很多地方,作者也在结论部分说它将被应用到图像、音频、视频等任务中,本文......
  • 【代码分享】使用 terraform, 在 Let's Encrypt 上申请托管在 cloudflare 上的域名对
    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢!cnblogs博客zhihuGithub公众号:一本正经的瞎扯运行的流程可以抽象为上图。直接贴代码:letsencrypt.tfterraform{required_providers{acme={source="vancluever/acme"version="......
  • 如何有效检测、识别和管理 Terraform 配置漂移?
    在理想的IaC世界中,我们所有的基础设施实现和更新都是通过将更新的代码推送到GitHub来编写和实现的,这将触发Jenkins或Circle-Ci中的CI/CD流水线,并且这些更改会反映在我们常用的公有云中。但现实并没有这么顺利,原因可能有很多,例如: 公司仍处于云自动化的初级阶段;不......
  • 如何有效检测、识别和管理 Terraform 配置漂移?
    作者|KrishnaduttPanchagnula翻译|Seal软件链接|https://betterprogramming.pub/detecting-identifying-and-managing-terraform-state-drift-997366a74537 在理想的IaC世界中,我们所有的基础设施实现和更新都是通过将更新的代码推送到GitHub来编写和实现的,这将触发Jenki......
  • Oracle EBS:注册Form表单和function功能基本操作
    OracleEBS:注册Form基本操作。这里将注册Form的基本步骤记录下来。1.首先,查看当前用户是否具备应用开发员责任。如果没有需要为当前登录用户配置应用开发员责任权限。2.配置完应用开发员角色后,打开oracleApplication表单界面,切换角色到应用开发员,打开应用产品,即可看到表单注......
  • Delta Lake_ High-Performance ACID Table Storage over Cloud Object Stores
    论文发表于2020年,研究数据湖产品的很好的学习资料.概要开篇很明确的表明了为什么要做Deltalake这样一个产品.Databricks尝试将数据仓库直接架在云上对象存储之上,这种尝试的过程中遇到了对象存储的一些问题,为了解决这些问题,提出了Deltalake这套技术方案.对象存储的......
  • BatchNorm
    BatchNorm层【对数据进行归一化】位置:全连接层:仿射变换与激活函数之间卷积层:卷积层后与激活函数之前作用:①加快收敛速度;②防止梯度爆炸/梯度消失③防止过拟合......
  • 使用vue3、egg和SQLite开发通用管理后台系统
    使用vue3、egg和SQLite开发通用管理后台系统plaform是一个基于RBAC模型开发的后台管理系统,没有多余的功能。本项目是一个以学习为目的的后台项目,旨在让前端也能充分了解RBAC模型是如何设计的,不建议用于线上,因为未经过充分的测试。项目地址:https://github.com/essay-org/platform......