Question

I am developing a service to collect data from many remote databases and compile it to a master database. I have an interface which contains data that is common between the two databases. The interface also serves as the link between my Model and ViewModel.

I would like to take the data from an instance of RemoteDatabase and put all of that into an instance of MasterDatabase.

public interface IInterface
{
    //Common interface properties in both databases
    long PK { get; set; }
    Nullable<long> RUN_ID { get; set; }
    string Recipe_Name { get; set; }
    string Notes { get; set; }
    //Lots more properties from a database
}

class RemoteDatabase : IInterface
{
    //Common interface properties in both databases
    public long PK { get; set; }
    public Nullable<long> RUN_ID { get; set; }
    public string Recipe_Name { get; set; }
    public string Notes { get; set; }
    //Lots more properties from a database
}

class MasterDatabase : IInterface
{
    //Additional properties that Remote Database doesn't have
    public int locationFK { get; set; }

    //Common interface properties from database
    public long PK { get; set; }
    public Nullable<long> RUN_ID { get; set; }
    public string Recipe_Name { get; set; }
    public string Notes { get; set; }
    //Lots more properties from a database

    public MasterDatabase(IInterface iInterface)
    {
        var interfaceProps = typeof(IInterface).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo p in interfaceProps)
        {
            p.Name;
        }
    }
}

I tried to just cast the object, but that provided an invalid cast exception, which I understand (although they have common ancestors, that doesn't mean they can cast dog==animal, fish==animal, but dog!=fish, but what I want is to get the common properties defined in IAnimal).

Since I couldn't cast, I would like to use reflection so that if the interface updates then all of the new objects in the MasterDatabase class will update automatically. I used reflection to get all of the properties from the interface, but now how do I use the propertyInfo.name to get the values in the MasterDatabase class.

Perhaps I am missing something obvious, or there is a far better way to do this. I appreciate any help or suggestions.

Thank you in advance.

Était-ce utile?

La solution

You need to call SetValue on the PropertyInfo object, using this as the target. The value you pass should be retrieved using a corresponding GetValue call on the constructor parameter:

foreach (PropertyInfo p in interfaceProps)
{
    p.SetValue(this, p.GetValue(iInterface, null), null);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top