代码之家  ›  专栏  ›  技术社区  ›  B2K

Razor视图的Duck打字

  •  1
  • B2K  · 技术社区  · 9 年前

    我有一个数据会话模型,其中包含许多不同类型的申请人。所有这些都有FirstName和LastName属性,我想在剃刀视图中显示它们。

    var applicant = model.Lead ??
                    model.Drivers.FirstOrDefault() ??
                    model.Loans.FirstOrDefault() ?? 
                    model.Renewals.FirstOrDefault();
    

    乍一看,我会使用继承,但这些是EF数据库中的类,不确定如何设置父类。

    有没有一个干净的方法来做这件事,或者我被这样的事情卡住了?

    dynamic applicant = new ExpandoObject();
    
    if (model.Lead != null) {
       applicant.FirstName = model.Lead.FirstName;
       applicant.LastName = model.Lead.LastName;
    } else if ( model.Drivers.Any() ) {
       var first = model.Drivers.FirstOrDefault();
       applicant.FirstName = first.FirstName;
       applicant.LastName = first.LastName;
    } else if ...
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   Anish Patel    9 年前

    您可以使用接口。

    假设您的EF代码生成模型如下所示:

    public partial class Driver {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        // other properties ...
    }
    
    public partial class Loan {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        // other properties ...
    }
    
    public partial class Renewal {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        // other properties ...
    }
    
    public partial class Lead {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        // other properties ...
    }
    

    然后创建一个定义公共属性的接口:

    public interface IApplication {
        string FirstName { get; set; }
        string LastName { get; set; }
    }
    

    然后 使生效 该接口:

    public partial class Driver : IApplication {}
    
    public partial class Loan : IApplication {}
    
    public partial class Renewal : IApplication {}
    
    public partial class Lead : IApplication {}
    

    然后将视图中的模型设置为:

    @model IEnumerable<IApplication>
    

    然后,您可以返回一个填充了不同具体类型的IEnumerable集合,并访问接口上定义的公共属性。