I want to be able to create a custom validator, that will allow me to connect to my database and tell me (for example) whether a name is unique. I used to use the [Remote] attribute in EF, but I have read that you cannot use this with Blazor.
The Validation code I have so far is this:
public class LandlordNameIsUniqueValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//This is always null
var context = (ApplicationDbContext)validationContext.GetService(typeof(ApplicationDbContext));
var checkName = new LandlordData(context);
var name = value.ToString();
var nameExists = checkName.CheckNameIsUnique(name);
if (!exists)
{
return null;
}
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
The code I use (successfully in other parts of the application) is as follows, this will return a bool:
public class LandlordData : ILandlordData
{
private readonly ApplicationDbContext _context;
public LandlordData(ApplicationDbContext context)
{
_context = context;
}
public bool CheckNameIsUnique(string name)
{
var exists = _context.Landlords
.AsNoTracking()
.Any(x => x.LandlordName == name);
return exists;
}
}
In StartUp.cs
is as follows:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
_config.GetConnectionString("DefaultConnection")),
ServiceLifetime.Transient);
I also have this service registered, which I use in my Blazor pages, successfully.
services.AddTransient<ILandlordData, LandlordData>();
Despite numerous attempts and different methods, I cannot (more likely I don't know how to) inject the DbContext
, so I can use the LandlordData Class
to check the record.
But my ApplicationDbContext
is always null!
Can anyone advise the correct approach to access my database to perform custom validation.
TIA