2

I have a table derived from base class. So, the derived table will have same id as base table. like

public class Animal
{
public int AnimalId{get; set;}
public string Name{get;set;}
}

public class Man:Animal
{
//Primary key as well as foreign key will be AnimalId. 
public string Communicate{get;set;}
}

Now, although I can use ManId as the primary key in the database and use fluent api to let the classes know that the ManId is Base class AnimalId, I have no way to striaghtway use ManId in my poco classes and in programming.

So, I used viewmodel, gave the property name ManId for using in my classes and views. I am using ValueInjector to map between model and viewmodel.

The problem I am stuck in and seeking the solution whole morning is: valueinjector could not inject the AnimalId to ManId as the name is not the same.

I found that the solution could be .. using conventioninjection to override the defaults but I could not implement it properly.

public class PropertyMismatch:ConventionInjection
{
    protected override bool Match(ConventionInfo c)
    {
        return ((c.TargetProp.Name == "ManId" && c.SourceProp.Name == "AnimalId") ||
            (c.SourceProp.Name==c.TargetProp.Name &&                            c.SourceProp.Value==c.TargetProp.Value));

    }


}

If any one knows the solution, it should be of great help to me. Thanx very much in advance to all the viewers and solvers.

Bibek Maharjan
  • 549
  • 2
  • 5
  • 15

1 Answers1

4

Try this:

class Program
{
    static void Main( string[] args )
    {
        Animal animal = new Animal() { AnimalId = 1, Name = "Man1" };
        Man man = new Man();
        man.InjectFrom<Animal>( animal );
    }
}

public class Animal:ConventionInjection
{
    public int AnimalId { get; set; }
    public string Name { get; set; }

    protected override bool Match( ConventionInfo c )
    {
        return ((c.SourceProp.Name == "AnimalId") && (c.TargetProp.Name == "ManId"));
    }
}

public class Man : Animal
{

    public int ManId { get; set; } 
    public string Communicate { get; set; }
}
KrishnaDhungana
  • 2,604
  • 4
  • 25
  • 37
  • 1
    Thanks very much for the solution. It worked perfectly fine. I had to make one small modification for my solution as follows: return ((c.SourceProp.Name == "AnimalId") && (c.TargetProp.Name == "ManId") || (c.SourceProp.Name == c.TargetProp.Name)); – Bibek Maharjan Dec 09 '13 at 11:32
  • Also, I did the above mentioned override in the Man POCO Class and left the Animal POCO class's override method with the not implemented exception so that if someone tried other way round, it will throw an exception. – Bibek Maharjan Dec 09 '13 at 11:42