开发者

Merging 2 models into 1 model in MVC

I don't know exactly the term of my problem, maybe thats the reason why I can not find such relevant issues in here.

Say, I have these models.

public abstract class Member
{
   public string ID { get; set; }
   public string Username { get; set; }
   public int  MemberType { get; set; } //1 if person; 2 if business
   //public string MemberName { get; set; } 
}

public class Person : Member
{
   public string LastName { get; set; }
   public string FirstName{ get; set; }
}

public class Business : Member
{
   public string BusinessName { get; set; }
   public string TaxNo { get; set; }
}

Right now, I do not have a problem on accessing those models usin开发者_运维问答g fluent API.

Now, what I want to achieve is to add a property on my Member class which is MemberName, which will be derived from LastName and FirstName property of Person class if MemberType is 1 and BusinessName of Business class if MemberTYpe = 2.

Is there an easy way to achieve this kind of thing?

Thanks


This can be done with a bit of abstract magic.

On Member have this:

public abstract string MemberName { get; } 

Then on Person you override as:

public override string MemberName
{
   get{ return FirstName + " " + LastName; }
}

on Business you override as such:

public override string MemberName
{
   get{ return BusinessName; }
}

Now, any instanceof any class which inherits Member, when calling the MemberName property will return the right representation. This is all basic inheritance/OOP/Polymorphism whatever you want to call it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜