设置uuid
namespace EF6SQLiteTutorial.Models
{
public class People
{
public int Id { get; set; }
// 设置uuid
public Guid Uuid { get; set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public int age { get; set; } = 18;
public string sex { get; set; } = "male";
}
}
创建前检查
using EF6SQLiteTutorial.Data;
using EF6SQLiteTutorial.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace EF6SQLiteTutorial.Controllers
{
[Route("api/[controller]")] // https://localhost:7115/api/RpgCharacter
[ApiController]
public class RpgCharacterController : ControllerBase
{
private readonly DataContext _context;
public RpgCharacterController(DataContext context)
{
_context = context;
}
[HttpPost]
public async Task<ActionResult<List<RpgCharacter>>> AddCharacter(RpgCharacter character)
{
var existingRPG = await _context.RpgCharacters.FirstOrDefaultAsync(c => c.Name == character.Name);
if (existingRPG != null)
{
// 如果存在,则返回一个错误消息
return BadRequest("A rpg with the same name already exists.");
}
_context.RpgCharacters.Add(character);
await _context.SaveChangesAsync();
return Ok(await _context.RpgCharacters.ToListAsync());
}
}
}
unique约束
using Microsoft.EntityFrameworkCore;
using EF6SQLiteTutorial.Models;
namespace EF6SQLiteTutorial.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<RpgCharacter> RpgCharacters => Set<RpgCharacter>();
public DbSet<People> Peoples => Set<People>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 设置RPG角色的name唯一,unique约束
modelBuilder.Entity<RpgCharacter>()
.HasIndex(c => c.Name)
.IsUnique();
}
}
}