到目前为止,我一直在验证我的dto属性的现有值,最小值,最大值,长度等。
现在我的http api有一个用例,其中http post的有效负载包含数据库中不存在的Ids(数据库外键),或者这些ID不属于持有者令牌中的userId。 UserId始终是每个表中的一个字段。
我是否应该真正编写一个存储库方法,如:
// done with 3 queries still room for optimization...
public bool NewTestTypeIsValid(string userId,int schoolyearId, int schoolclassId, int subjectId)
{
return context.TestTypes.SingleOrDefault(x => x.userId == userId && x.schoolyearId == schoolyearId) != null &&
context.Schoolclasses.SingleOrDefault(x => x.userId == userId && x.schoolclassId == schoolclassId) != null &&
context.Subjects.SingleOrDefault(x =>x.userId == userId && x.subjectId == subjectId) != null;
}
检查测试类型的http帖子是否有效/无效,如果无效,则返回400个错误数据?
为了使问题更难回答,我提出了一个更真实的样本:
当这个数据被http发布到服务器时,我不仅需要验证subjectId,schoolclassId,schoolyearId,还要验证每个 TestTypeId
已更新 TestType 的
数据不是来自REST端点,它只是我需要的肥皂风格: - )
public async Task<IEnumerable<TestType>> SaveTestTypesAsync(List<TestType> testTypes, int schoolyearId, int schoolclassId, int subjectId, string userId)
{
var testTypesFromDatabase = await context.TestTypes
.Include(t => t.Subject)
.Include(s => s.Schoolclass)
.Where(p =>
p.Schoolclass.Id == schoolclassId &&
p.Subject.Id == subjectId && p.UserId == userId
)
.AsNoTracking()
.ToListAsync();
var schoolclass = new Schoolclass { Id = schoolclassId };
var subject = new Subject { Id = subjectId };
var schoolyear = new Schoolyear { Id = schoolyearId };
// Make the navigation properties available during SaveChanges()
context.Attach(schoolclass);
context.Attach(subject);
context.Attach(schoolyear);
// DELETE
var testTypesToRemove = testTypesFromDatabase.Except(testTypes, new TestTypeComparer()).ToList();
context.TestTypes.RemoveRange(testTypesToRemove);
// ADD
var testTypesToAdd = testTypes.Where(t => t.Id == 0).ToList(); //
foreach (var testType in testTypesToAdd)
{
testType.Schoolclass = schoolclass;
testType.Subject = subject;
testType.Schoolyear = schoolyear;
}
context.TestTypes.AddRange(testTypesToAdd);
// UPDATE
var modifiedTestTypesToUpdate = testTypes.Except(testTypesToAdd.Concat(testTypesToRemove).ToList(), new TestTypeComparer()).ToList();
foreach (var testType in modifiedTestTypesToUpdate)
{
testType.Schoolclass = schoolclass;
testType.Subject = subject;
testType.Schoolyear = schoolyear;
}
context.UpdateRange(modifiedTestTypesToUpdate);
await context.SaveChangesAsync();
return await this.GetTestTypesConfigurationAsync(schoolclassId, subjectId, userId);
}