当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Duck Typing for Razor views

问题描述:

I have a data session model which contains many different types of applicants. All of these have FirstName and LastName properties which I would like to display in a razor view.

var applicant = model.Lead ??

model.Drivers.FirstOrDefault() ??

model.Loans.FirstOrDefault() ??

model.Renewals.FirstOrDefault();

At first glance, I would use inheritance, except that these are classes in an EF database, not sure how to setup a parent class.

Is there a clean way to do this or am I stuck with something like this?

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 ...

网友答案:

You can use an interface.

Assuming your EF code generated models look like this:

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

Then create an interface that defines the common properties:

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

Then implement that interface:

public partial class Driver : IApplication {}

public partial class Loan : IApplication {}

public partial class Renewal : IApplication {}

public partial class Lead : IApplication {}

Then set the model in your view to:

@model IEnumerable<IApplication>

And then you can return an IEnumerable collection filled with different concretes types and access the common properties which are defined on the interface.

分享给朋友:
您可能感兴趣的文章:
随机阅读: