如何解决如何使用Asp.net Core防止Blazor服务器端出现重复记录
我在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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。