数据注释始终搜索父模型的属性

时间:2015-11-02 21:10:30

标签: asp.net-mvc data-annotations system.reflection

更新

我已经意识到这个问题的根本原因,并在另一个问题中详细说明了这里:How Can I Use Custom Validation Attributes on Child Models of a DB Entity?

我有一个WebsiteConfiguration模型,它包含许多子模型,为方便起见,这些模型按此类细分。

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; }
}

我正在尝试将DataAnnotation添加到其中一个子模型中,如果另一个标记为true,则需要某些属性。像这样:

public class SocialMediaLoginsConfiguration
{
    public bool Initialised { get; set; }

    public bool IsLoginWithFacebookEnabled { get; set; }

    [RequiredIfEnabled("IsLoginWithFacebookEnabled")]
    public string LoginWithFacebookAppID { get; set; }

    [RequiredIfEnabled("IsLoginWithFacebookEnabled")]
    public string LoginWithFacebookAppSecret { get; set; }
}

DataAnnotation代码是:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class RequiredIfEnabledAttribute : ValidationAttribute
{
    private string _ifWhatIsEnabled { get; set; }


    public RequiredIfEnabledAttribute(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;
    }
}

当我尝试获取IsLoginWithFacebookEnabled的值时,它会在WebsiteConfiguration类中查找此属性,而不是SocialMediaLoginsConfiguration。即使注释属性在后者中。

如何让它在与注释相同的类中查找属性?

更新

我认为这种情况正在发生,因为我在网站配置上调用DB.SaveChanges(),如下所示:

    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();
    }

但我不想为每个子模型创建单独的数据库表。我希望它们存储在一个表中,但在代码中我希望将它们作为子模型进行管理。

0 个答案:

没有答案