0

I am writing a code to map certain properties from one object to another except the Navigational properties.

My code looks something like this:

var properties = typeof(TOne).GetProperties();

var t = new TOne();
foreach (var prop in properties)
{
    var skip = exempt == null || (exempt != null && exempt.Contains(prop.Name));

    if (!skip &&  CommonHelper.HasProperty(obj, prop.Name))
    {           
        var _prop = obj.GetType().GetProperty(prop.Name);                    
        CommonHelper.SetPropValue(t, prop.Name, _prop.GetValue(obj, null));                    
    }
}

I would like to skip all the navigational properties (do not wish to copy object but primitive types).

For example:

class Person {
    public int Id { get; set; }

    [ForeignKey("DetailId")]
    public Detail Detail { get; set; }

    public int DetailId { get; set; }
}

I wish to copy DetailId but not the Detail object.

Rishabh Sharma
  • 103
  • 1
  • 2
  • 14
  • 1
    Automapper is your friend (https://automapper.org). nobody bothers to write this kind of copy code anymore in my experience – jazb Nov 27 '18 at 06:50
  • Hi JohnB, thanks for your suggestion but I would like to learn to write one myself. – Rishabh Sharma Nov 27 '18 at 06:52
  • Is EF context metadata accessible for your mapper? If so, what EF version do you use (metadata were changed from v6 to v7)?. – Dennis Nov 27 '18 at 07:02
  • EF context metadata is accessible and I am using EF v6. – Rishabh Sharma Nov 27 '18 at 07:03
  • 1
    Have you looked at doing something like this using Type.IsPrimitive? https://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive – Eric H Nov 27 '18 at 14:05

2 Answers2

0

Thanks Eric H.

I think this would work for me where we compare the type of the value of the property. Here, we are checking whether the type of value of the property is Object:

object valueOfProperty = ...
if(Convert.GetTypeCode(valueOfProperty) != TypeCode.Object){
   // Do something
}
Rishabh Sharma
  • 103
  • 1
  • 2
  • 14
0

In entity framework the columns of the tables are represented by non-virtual properties. The virtual properties represent the relations between the tables (one-to-many, many-to-many, ...)

You should have defined your property Detail as a virtual property. After all, it is not a real Detail item in your tables.

Once you've declared all relational properties virtual, you'll only have to process the non-virtual properties.

See How to find out whether a property is virtual

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116