【问题标题】:EF Data Annotation - Foreign Key - How to CustomizeEF 数据注解 - 外键 - 如何自定义
【发布时间】:2014-03-25 17:11:49
【问题描述】:

我的问题如下。我有一个地址表的模型,如下所示。

public partial class ADDRESS
{
    public ADDRESS()
    {
        this.ADDRESS_ID = Guid.NewGuid();
    }

    public Guid ADDRESS_ID { get; set; }
    public string ADDRESS_LINE { get; set; }
    public string CITY { get; set; }
    public Guid? STATE_ID { get; set; }
    public string ZIP { get; set; }
}

此 ADDRESS 模型在我的整个应用程序中使用,并且根据它在表单中的放置位置具有不同的验证要求。

我想知道是否有办法自定义数据注释。例如,OCCUPATION_ADDRESS 需要 ADDRESS_LINE 和 CITY 属性,但 WORK_LOCATION_ADDRESS 不需要。

public class OCCUPATION_DETAILS
{
    public string COMPANY_NAME { get; set; }
    public string JOB_TITLE { get; set; }
    etc...

    public Guid OCCUPATION_ADDRESS_ID { get; set; }
    public virtual ADDRESS OCCUPATION_ADDRESS { get; set; }

    public WORK_LOCATION_ID { get; set; }
    public virtual ADDRESS WORK_LOCATION_ADDRESS { get; set; }

}

或者可能是基本验证相同(zip 必须为 5 位数字),但我需要调整用于匹配其所在表单标签的“DisplayName”。

尽量减少我设置的复制模型的数量;否则维护将是一场噩梦。

【问题讨论】:

    标签: entity-framework model-view-controller data-annotations


    【解决方案1】:

    你可以通过继承的思想来实现这一点 如何?

    public abstract class ADDRESS
    {
        public ADDRESS()
        {
            this.ADDRESS_ID = Guid.NewGuid();
        }
    
        public Guid ADDRESS_ID { get; set; }
        public string ADDRESS_LINE { get; set; }
        public string CITY { get; set; }
        public Guid? STATE_ID { get; set; }
        public string ZIP { get; set; }
    }
    
    public parital class OCCUPATION_ADDRESS: ADDRESS,IValidatableObject
    {
       public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
       {
           if(string.IsNullOrWhiteSpace(ADDRESS_LINE))
              yield return new ValidationResult("Address line is required!",new string[]{"ADDRESS_LINE"});
       }
    }
    
    public parital class WORK_LOCATION_ADDRESS: ADDRESS,IValidatableObject
    {
       public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
       {
    
       }
    }
    
    // and your Occupation details class will be like: instead of ADDRESS you will use the corresponding derived classes
    public class OCCUPATION_DETAILS
    {
        public string COMPANY_NAME { get; set; }
        public string JOB_TITLE { get; set; }
        etc...
    
        public Guid OCCUPATION_ADDRESS_ID { get; set; }
        public virtual OCCUPATION_ADDRESS OCCUPATION_ADDRESS { get; set; }
    
        public WORK_LOCATION_ID { get; set; }
        public virtual WORK_LOCATION_ADDRESS WORK_LOCATION_ADDRESS { get; set; }
    
    }
    

    并且继承应该是 Table per Hierarchy (TPH)

    有关 TPH 的更多信息,请查看Table per hierarchy

    希望对你有帮助

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2017-07-16
      • 1970-01-01
      • 2016-06-11
      • 2021-11-07
      • 1970-01-01
      相关资源
      最近更新 更多