新建 .net core项目
NuGet程序包中添加以下包:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Pomelo.EntityFrameworkCore.MySql
Newtonsoft.Json
设计三个类:User、Department、Product 其中User与Department是一对一关系,User与Product是一对多关系。
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EFCoreLearn.Models
{
[Table("t_user")]
public class User
{
[Key]
public string id { get; set; }
public string name { get; set; }
public string password { get; set; }
public Department department { get; set; }
public List<Product> products { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EFCoreLearn.Models
{
[Table("t_department")]
public class Department
{
[Key]
public string id { get; set; }
public string departmentName { get; set; }
public string userId { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EFCoreLearn.Models
{
[Table("t_product")]
public class Product
{
[Key]
public string id { get; set; }
public string productName { get; set; }
public string userId { get; set; }
}
}
创建CustomMigrationsSqlGenerator类,编写代码取消数据库迁移时生成的外键。
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EFCoreLearn.Models
{
public class CustomMigrationsSqlGenerator : MigrationsSqlGenerator
{
public CustomMigrationsSqlGenerator(MigrationsSqlGeneratorDependencies dependencies, IMigrationsAnnotationProvider migrationsAnnotations) : base(dependencies)
{
}
protected override void Generate(Microsoft.EntityFrameworkCore.Migrations.Operations.CreateTableOperation operation, IModel? model, MigrationCommandListBuilder builder, bool terminate = true)
{
operation.ForeignKeys.Clear();
base.Generate(operation, model, builder, terminate);
}
}
}
创建UserContext类继承DbContext,重写OnConfiguring方法,在方法中应用刚才写的CustomMigrationsSqlGenerator
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EFCoreLearn.Models
{
public partial class UserContext : DbContext
{
public UserContext()
{
}
public UserContext(DbContextOptions<UserContext> options) : base(options)
{
}
//这行代码定义了一个 User 属性,该属性表示数据库中的用户表。
//通过在 DbContext 中声明这样的属性,Entity Framework Core 就能够跟踪和操作与该实体类相关联的数据库表。
//当你对 User 属性进行查询、插入、更新或删除时,
//Entity Framework Core 会负责将这些操作转化为相应的 SQL 查询并与数据库进行交互。
public DbSet<User> User { get; set; } = null!;
public DbSet<Department> department { get; set; } = null!;
public DbSet<Product> product { get; set; } = null!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.ReplaceService<IMigrationsSqlGenerator, CustomMigrationsSqlGenerator>();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.UseCollation("utf8_general_ci").HasCharSet("utf8");
modelBuilder.Entity<User>().HasMany(e => e.products); //user 与 product一对多
modelBuilder.Entity<User>().HasOne(e => e.department); //user 与 department 一对一
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
执行数据库迁移(根据代码配置自动生成数据库表)
在vs的程序包管理控制台中输入
add-migration init
update-database
检查数据库中生成的表
写接口测试
using EFCoreLearn.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace EFCoreLearn.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
UserContext userContext;
public TestController(UserContext userContext)
{
this.userContext = userContext;
}
/// <summary>
/// 添加用户 部门 产品
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
[HttpPost("add")]
public ObjectResult add()
{
User user = new User();
user.id = Guid.NewGuid().ToString();
user.name = "zhangsan";
user.password = "123456";
user.department = new Department {
id = Guid.NewGuid().ToString(),
departmentName = "IT部",
userId = user.id
};
user.products = new List<Product> {
new Product {id=Guid.NewGuid().ToString(),productName="键盘",userId=user.id},
new Product {id=Guid.NewGuid().ToString(),productName="鼠标",userId=user.id}
};
userContext.User.Add(user);
userContext.SaveChanges();
return new ObjectResult("ok");
}
/// <summary>
/// 添加用户
/// </summary>
/// <returns></returns>
[HttpPost("addUser")]
public ObjectResult addUser() {
User user = new User();
user.id = Guid.NewGuid().ToString();
user.name = "lisi";
user.password = "123456";
userContext.User.Add(user);
userContext.SaveChanges();
return new ObjectResult("ok");
}
/// <summary>
/// 获取列表(用户 部门 产品)
/// </summary>
/// <returns></returns>
[HttpGet("list")]
public ActionResult list()
{
//var list = userContext.User.Include(a => a.products).Include(a=>a.department).Single<User>(e=>e.id=="03038eca-4b53-4b31-87dc-de5b568923a4");
var list = userContext.User.Include(a => a.products).Include(a => a.department).ToList();
if (list == null)
{
return new JsonResult("list is null");
}
var result = JsonConvert.SerializeObject(list);
return Content(result, "application/json");
}
/// <summary>
/// 更新 用户 部门 产品
/// </summary>
/// <returns></returns>
[HttpPut("update")]
public ObjectResult update() {
User user = new User();
user.id = "03038eca-4b53-4b31-87dc-de5b568923a4"; //要修改的用户的id
user.name = "zhangsan_update";
user.password = "123456_update";
user.department = new Department
{
id = "a099a496-cde0-4495-9701-afd79228be8d",
departmentName = "IT部_update",
userId = user.id
};
user.products = new List<Product> {
new Product {id="2afbf390-49d2-4737-bba4-c8fbcb160914",productName="键盘_update",userId=user.id},
new Product {id="92bcbc28-b671-47a1-9a3c-24faba8338a9",productName="鼠标_update",userId=user.id}
};
userContext.User.Update(user);
userContext.SaveChanges();
return new ObjectResult("ok");
}
/// <summary>
/// 更新 用户
/// </summary>
/// <returns></returns>
[HttpPut("updateUser")]
public ObjectResult updateUser()
{
User user = new User();
user.id = "5705f49f-0d24-4723-a524-f14808a59274"; //要修改的用户的id
user.name = "lisi_update";
user.password = "123456_update";
userContext.User.Update(user);
userContext.SaveChanges();
return new ObjectResult("ok");
}
}
}
3 条评论
建议增加个人经历分享,增强情感穿透力。
《百分百歌手》大陆综艺高清在线免费观看:https://www.jgz518.com/xingkong/1898.html