Search code examples
c#sql-server-2008entity-frameworkinheritancevalueinjecter

Mapping different property values using value injector


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.


Solution

  • 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; }
    }