首页 > 解决方案 > 使用数据库优先方法的 WPF 中的 DataAnnotation - 如何将数据注释移动到伙伴类,包括。IsValid 函数

问题描述

正如主题中简短描述的那样:如何将所有 DataAnnotations 从模型移动到元数据模型,以便在更新 edmx 时不将其清除?
换句话说,我希望数据注释安全并且不会随着 edmx 的每次更新而被删除,并且我将在 dataannotation 中有一个选项来检查是否满足所有数据注释要求(IsValid 方法)以在 RelayCommand 的 CanExecute 方法中使用它.

我有一堂课如下:

public partial class Customer : IDataErrorInfo
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public int ID{ get; set; }

    [Required(ErrorMessage = "Field required")]
    public string Name{ get; set; }

    [Required(ErrorMessage = "Field required")]
    public string LastName{ get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<tblKontrahent> tblKontrahent { get; set; }


    #region Validation
    public bool IsValid { get; set; } 

    public string Error { get { return null; } }

    public string this[string columnName]
    {
        get
        {
            Validation();
            return InputValidation<Customer >.Validate(this, columnName);
        }
    }

    public ICollection<string> AllErrors()
    {
        return InputValidation<Customer >.Validate(this);
    }

    private void Validation()
    {
        ICollection<string> allErrors = AllErrors();
        if (allErrors.Count == 0)
            IsValid = true;
        else
            IsValid = false;
    }
    #endregion


    #region Shallow copy
    public Customer ShallowCopy()
    {
        return (Customer )this.MemberwiseClone();
    }
    #endregion
}

如何使用注释和 IsValid 函数将其从 Model 移动到 MetaDataModel。如果 ShallowCopy 方法也可以移动,那就太好了。

非常感谢您的任何建议!

标签: c#wpfdata-annotationsef-database-firstbuddy-class

解决方案


对于大多数实质性应用程序,我将 EF 类完全分开。我将属性从实体框架复制到自我跟踪的视图模型。

对于较小的应用程序,我曾经避免这样做。

您可以看到其中使用的一种方法:

https://gallery.technet.microsoft.com/scriptcenter/WPF-Entity-Framework-MVVM-78cdc204

它使用 INotifyDataErrorInfo,您会在 BaseEntity 中找到 IsValid。这是一个相当复杂但可重复使用的类。

您可能可以将浅拷贝重构为 BaseEntity。如果您可以在任何使用它的地方轻松投射。

注释在单独的伙伴类中。您可以在 Customer.metadata.cs 和 Product.metadata.cs 中看到示例。这些是向实体类添加对 BaseEntity 的继承的部分类。因此,EF 类 Customer 继承了 BaseEntity。

一个例子:

using DataAnnotationsExtensions;

namespace wpf_EntityFramework.EntityData
{
[MetadataTypeAttribute(typeof(Product.ProductMetadata))]
public partial class Product : BaseEntity, IEntityWithId
{
    public void MetaSetUp()
    {
        // In wpf you need to explicitly state the metadata file.
        // Maybe this will be improved in future versions of EF.
        TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Product),
            typeof(ProductMetadata)),
            typeof(Product));
    }
    internal sealed class ProductMetadata
    {
        // Some of these datannotations rely on dataAnnotationsExtensions ( Nuget package )
        [Required(ErrorMessage="Product Short Name is required")]
        public string ProductShortName { get; set; }

        [Required(ErrorMessage = "Product Weight is required")]
        [Min(0.01, ErrorMessage = "Minimum weight is 0.01")]
        [Max(70.00, ErrorMessage = "We don't sell anything weighing more than 70Kg")]
        public Nullable<decimal> Weight { get; set; }

        [Required(ErrorMessage = "Bar Code is required")]
        [RegularExpression(@"[0-9]{11}$", ErrorMessage="Bar codes must be 11 digits")]
        public string BarCode { get; set; }

        [Required(ErrorMessage = "Price per product is required")]
        [Range(0,200, ErrorMessage="Price must be 0 - £200") ]
        public Nullable<decimal> PricePer { get; set; }
        private ProductMetadata()
        { }
    }
}

}

正如其中的评论所说。

您需要在每个实例上调用该 Metasetup。除非最近几年发生了一些变化。伙伴类不只是像 MVC 那样被拾取。

该示例还从 UI 反馈转换失败。

请参阅 Dictionary1 中的模板。

<ControlTemplate x:Key="EditPopUp" TargetType="ContentControl">
    <ControlTemplate.Resources>
        <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource ErrorToolTip}">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ControlTemplate.Resources>
    <Grid Visibility="{Binding IsInEditMode, Converter={StaticResource BooleanToVisibilityConverter}}" 
           Width="{Binding ElementName=dg, Path=ActualWidth}"
           Height="{Binding ElementName=dg, Path=ActualHeight}"
           >
                <i:Interaction.Triggers>
                    <local:RoutedEventTrigger RoutedEvent="{x:Static Validation.ErrorEvent}">
                        <e2c:EventToCommand
                                                Command="{Binding EditVM.TheEntity.ConversionErrorCommand, Mode=OneWay}"
                                                EventArgsConverter="{StaticResource BindingErrorEventArgsConverter}"
                                                PassEventArgsToCommand="True" />
                    </local:RoutedEventTrigger>
                    <local:RoutedEventTrigger RoutedEvent="{x:Static Binding.SourceUpdatedEvent}">
                        <e2c:EventToCommand
                                                Command="{Binding EditVM.TheEntity.SourceUpdatedCommand, Mode=OneWay}"
                                                EventArgsConverter="{StaticResource BindingSourcePropertyConverter}"
                                                PassEventArgsToCommand="True" />
                    </local:RoutedEventTrigger>
                </i:Interaction.Triggers>

推荐阅读