简体   繁体   中英

ASP.NET Core validate Azure Table Entity already taken

I'm trying to trigger a data validation error back to my view on a lookup to a database back end.

// Perform lookup to see if domain has been taken already
var domainResults = await _context.TenantEntity.SingleOrDefaultAsync(x => x.Office365DomainName == Input.Office365DomainName);
if (domainResults.Office365DomainName == Input.Office365DomainName)
{
    // duplicate domain name attempted
    user.Office365DomainName = "AlreadyTaken";
    return Page();
}

Here is my field:

[Required]
[Display(Name = "Office 365 Domain Name")
public string Office365DomainName { get; set; }

I'd prefer to use a DataAnnotation so I can send back a custom message to the view/user but I'm at a loss on how to build this in.

I've tried changing my property validation to a regex and watching for "AlreadyTaken" as I'm setting this inside my class which contains the same object. My thought was to perform a regex match on something obscure (like a GUID) then have my regex match that GUID for a validation error.

I'm probably over thinking all this and I hope someone has some insight.

As suggested, there was a very easy answer to this:

// Perform lookup to see if domain has been taken already
var domainResult = await _context.TenantEntity.SingleOrDefaultAsync(x => x.Office365DomainName == Input.Office365DomainName);
if (domainResult != null && domainResult.Office365DomainName == Input.Office365DomainName)
{
    // duplicate domain name attempted
    ModelState.AddModelError("Office365DomainName", "This domain has been registered already.");
    return Page();
}

I didn't have to modify my field at all. The following article was a great help: https://exceptionnotfound.net/asp-net-mvc-demystified-modelstate/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM