问题描述
我在sql Server中使用Blazor服务器端。我想防止表中的重复记录。我不在sql Server中使用唯一索引。我想在插入数据库之前检查它吗?
Services.cs
using Test.Data;
using Test.Models.Moodle;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Test.Services.Moodle
{
public class MoodleService:IMoodleService
{
private readonly ApplicationDbContext _context;
public MoodleService(ApplicationDbContext context)
{
_context = context;
}
public async Task<List<MoodleTableModel>> Get()
{
return await _context.MoodleTablesList.ToListAsync();
}
public async Task<MoodleTableModel> Get(int id)
{
var moodle = await _context.MoodleTablesList.FindAsync(id);
return moodle;
}
public async Task<MoodleTableModel> Add(MoodleTableModel moodle)
{
_context.MoodleTablesList.Add(moodle);
await _context.SaveChangesAsync();
return moodle;
}
public async Task<MoodleTableModel> Update(MoodleTableModel moodle)
{
_context.Entry(moodle).State = EntityState.Modified;
await _context.SaveChangesAsync();
return moodle;
}
public async Task<MoodleTableModel> Delete(int id)
{
var moodle = await _context.MoodleTablesList.FindAsync(id);
_context.MoodleTablesList.Remove(moodle);
await _context.SaveChangesAsync();
return moodle;
}
}
}
解决方法
您可以使用dbcontext.MoodleTableList.Any()在插入之前检查db中是否有任何记录
, public async Task<bool> Add(MoodleTableModel moodle)
{//Condition to prevent duplicate
MoodleTableModel existingmoodle = await _dbContext.MoodleTableModel .FirstOrDefaultAsync(
m => m.Room== moodle.Room && m.Day== moodle.Day);
if (existingmoodle != null)
{
await Delete(moodle.Id);
}
else
{moodle.Id = Guid.NewGuid().ToString();
_dbContext.Add(moodle);
}
try
{
await _dbContext.SaveChangesAsync();
return true;
}
catch (DbUpdateException)
{
return false;
}
}