.net core 3.1 使用EntityFrameworkcore
程序员文章站
2024-03-02 14:54:46
...
首先安装 EntityFrameworkcore 注意版本5.0.0的不兼容
必须装用于运行命令,同样注意版本
使用最新版就好
使用最新版就好
这里可以运行命令
执行命令
Scaffold-DbContext "server=192.168.1.1;port=3306;user=test;password=123456;database=cloud;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force
执行后结果查看
需要在startup中注册
在项目中建立如下文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WLCloudAPI.Models;
namespace WLCloudAPI.Repositories
{
public interface ITestRepository
{
Task<IEnumerable<Test>> GetTestAsync();
Task<IEnumerable<Test>> GetTest();
Task<Test> GetTestAsync(int companyId);
void AddTest(Test company);
Task<bool> SaveAsync();
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WLCloudAPI.Models;
namespace WLCloudAPI.Repositories
{
class TestRepository : ITestRepository
{
private readonly wlcloudContext _myDbContext;
public TestRepository(wlcloudContext myDbContext)
{
_myDbContext = myDbContext ?? throw new ArgumentNullException(nameof(myDbContext));
}
public async Task<IEnumerable<Test>> GetTestAsync()
{
return await _myDbContext.Test.ToArrayAsync();
}
public async Task<IEnumerable<Test>> GetTest()
{
return await _myDbContext.Test.ToListAsync();
}
public async Task<Test> GetTestAsync(int companyId)
{
return await _myDbContext.Test.FirstOrDefaultAsync(x => x.Id == companyId);
}
public void AddTest(Test company)
{
_myDbContext.Test.Add(company);
}
public async Task<bool> SaveAsync()
{
return await _myDbContext.SaveChangesAsync() >= 0;
}
}
}
在webapi中的controller中使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WLCloudAPI.Models;
using WLCloudAPI.Repositories;
using WLCloudAPI.util;
namespace WLCloudAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class testController : Controller
{
private readonly ITestRepository _testRepository;
// 注入testRepository,就可以直接在控制器中使用其方法了
public testController(ITestRepository testRepository)
{
_testRepository = testRepository;
}
[HttpGet]
public async Task<IEnumerable<Test>> Get1()
{
return await _testRepository.GetTest();
}
}
配置文件读取类
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WLCloudAPI.util
{
public class AppSettingsHelper
{
public static IConfiguration Configuration { get; set; }
static AppSettingsHelper()
{
//ReloadOnChange = true 当appsettings.json被修改时重新加载
Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
}
}
}
推荐阅读