Podsumowanie:Jak używać niestandardowych atrybutów walidacji dla modeli potomnych jednostki DB?
chcę walidator adnotacji dane odwołać inną nieruchomość w tej samej klasie (TitleAuthorAndPublishingConfiguration
).
Jednak funkcja DB.SaveChanges() nie jest wywoływana bezpośrednio w tej klasie. Raczej jest wywoływany na rodzica tej klasy (WebsiteConfiguration
).
Dlatego validationContext.ObjectType
powraca WebsiteConfiguration
i nie mogę odwoływać się do właściwości TitleAuthorAndPublishingConfiguration
w walidatorze adnotacji danych.
WebsiteConfiguration.cs
public class WebsiteConfiguration
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public TitleAuthorAndPublishingConfiguration TitleAuthorAndPublishing { get; set; }
public BookChaptersAndSectionsConfiguration BookChaptersAndSections { get; set; }
public SocialMediaLoginsConfiguration SocialMediaLogins { get; set; }
public TagGroupsConfiguration TagGroups { get; set; }
}
public class TitleAuthorAndPublishingConfiguration
{
public string BookTitle { get; set; }
public bool IsPublished { get; set; }
// how do I access a property of current model when calling DB.SaveChanges() on parent?
[RequiredIfOtherFieldIsEnabled("IsPublished")]
public string Publisher { get; set; }
}
// ... and other sub models...
ApplicationDbContext.cs
DbSet<WebsiteConfiguration> WebsiteConfiguration {get;set;}
Przykład kodu Aktualizacja
public void SeedWebsiteConfiguration()
{
var titleAuthorAndPublishingConfiguration = new TitleAuthorAndPublishingConfiguration()
{
// seed values
};
var bookChaptersAndSectionsConfiguration = new BookChaptersAndSectionsConfiguration()
{
// seed values
};
var socialMediaLoginConfiguration = new SocialMediaLoginsConfiguration()
{
// seed values
};
var tagGroupsConfiguration = new TagGroupsConfiguration()
{
// seed values
};
var websiteConfiguration = new WebsiteConfiguration()
{
TitleAuthorAndPublishing = titleAuthorAndPublishingConfiguration,
BookChaptersAndSections = bookChaptersAndSectionsConfiguration,
SocialMediaLogins = socialMediaLoginConfiguration,
TagGroups = tagGroupsConfiguration
};
DB.WebsiteConfiguration.Add(websiteConfiguration);
DB.SaveChanges();
}
Code Validator
public class RequiredIfOtherFieldIsEnabledAttribute : ValidationAttribute
{
private string _ifWhatIsEnabled { get; set; }
public RequiredIfOtherFieldIsEnabledAttribute(string IfWhatIsEnabled)
{
_ifWhatIsEnabled = IfWhatIsEnabled;
}
protected override ValidationResult IsValid(object currentPropertyValue, ValidationContext validationContext)
{
var isEnabledProperty = validationContext.ObjectType.GetProperty(_ifWhatIsEnabled);
if (isEnabledProperty == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _ifWhatIsEnabled)
);
}
var isEnabledPropertyValue = (bool)isEnabledProperty.GetValue(validationContext.ObjectInstance, null);
if (isEnabledPropertyValue == true)
{
if (String.IsNullOrEmpty(currentPropertyValue.ToString()))
{
return new ValidationResult(String.Format("This field is required if {0} is enabled", isEnabledProperty));
}
}
return ValidationResult.Success;
}
}
Pytania
Czy istnieje sposób dla mnie, aby uzyskać dostęp do właściwości modelowych dziecko od
validationContext
?Czy jestem błędny w moim podejściu? Czy istnieje lepszy sposób przechowywania wielu modeli jako część większego modelu w jednej tabeli DB?
Miałem nadzieję, że nie będzie wielu tabel konfiguracyjnych i wywołań do DB. (W tym przykładzie są 4 modele potomne, ale w następnej aplikacji może być 10+).
Powyższe ustawienia spełniają moje potrzeby na tak wiele sposobów. Ale nie chcę rezygnować z funkcjonalności DataAnnotations na modelach podrzędnych!
Pytanie Bonus
mam natknąć kilka stanowisk jak ten: How can I tell the Data Annotations validator to also validate complex child properties?
Ale to jest 4 lat, i zastanawiam się, czy coś się zmieniło od tamtego czasu .
Czy próbuję zrobić coś, co jest zasadniczo niemożliwe (lub co najmniej bardzo trudne)?
'Jak mogę uzyskać dostęp do właściwości obecnego modelu Dzwoniąc DB.SaveChanges() na rodzica?' Jestem stara się zrozumieć, co znaczy ... jesteś chcąc uzyskać dostęp do członkowie klasy Wydawcy są wymagane? Czy chcesz to zrobić, używając adnotacji do danych? Jestem zdezorientowany i chciałbym to zrozumieć. –
Chcę walidatora adnotacji danych na właściwość 'TitleAuthorAndPublishingConfiguration', aby odwoływać się do innej właściwości' TitleAuthorAndPublishingConfiguration'. Ale 'DB.SaveChanges()' nie jest wywoływana bezpośrednio na tej klasie, a raczej na jej rodzica - 'WebsiteConfiguration'. –
Mam zaktualizowane pytanie, mam nadzieję, że będzie jaśniejsze –