Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8949177
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T13:10:29+00:00 2026-06-15T13:10:29+00:00

For all you Reflection experts I need some help. I am working on a

  • 0

For all you Reflection experts I need some help. I am working on a gneric method to be able to use hierarchical data assignments in an MVC application using CodeFirst and EF5. A user would apply changes to the parent object (source) and this method would populate the child object(s) (target). It’s not working as I would expect. Any pointers would be greatly appreciated.

The below method “CopyEntity” is intended to take a source entity that has child entities and update a target entity of the same type and structure. We are only looking to update those entities that inherit a base type of ‘Association’ and also do not have a ‘NoInherit’ attribute on the members. Not every property would be updated from the ‘Association’

public class ClassCode : Inheritable<ClassCode>
{

    // Base Properties ----------------------------------
    public int LobId { get; set; }
    public virtual LOB LOB { get; set; }
    public bool IsVirtual { get; set; }
    //public string Name { get; set; }
    public string Description { get; set; }

    [Required(ErrorMessage = "Select Code")]
    public string Code { get; set; }
    //enable to force recreation of the database
    public string IID { get; set; }

    public virtual ICollection<ClassSubjectivityAssoc> Subjectivities{ get; set; }
}

public class ClassSubjectivityAssoc : Association
{
    [Column("SubjectivityId")]
    public override int AssociationId { get; set; }

    [ForeignKey("AssociationId")]
    public virtual Subjectivity Subjectivity { get; set; }

    public int ClassCodeId { get; set; }
    [ForeignKey("ClassCodeId")]
    public virtual ClassCode ClassCode { get; set; }
}

public abstract class Association  : BaseEntity
{
    public DateTime Start { get; set; }
    public DateTime? End { get; set; }
    public bool IsCurrent { get; set; }
    public int Order { get; set; }
    public bool BreakInheritance { get; set; }
    public int? InhId { get; set; }
    public virtual ClassCode InhClass { get; set; }
    public int CodeId { get; set; }
    [ForeignKey("ClassCodeId")]
    public virtual Code ClassCode { get; set; }
    public abstract int AssociationId {get; set;}
}

public class BaseEntity
{
    private static DateTime CREATE_DATE
    {
        get { return DateTime.Now; }
    }

    [NoInherit]
    public int Id { get; set; }

    [NoInherit]
    public string CreatedBy { get; set; }
    [NoInherit]
    public DateTime Created { get; set; }

    [NoInherit]
    public string LastModifiedBy { get; set; }
    [NoInherit]
    public DateTime LastModified { get; set; }

    public bool IsActive { get; set; }
}

protected void CopyEntity(Inheritable<T> source, Inheritable<T> target)
{
    Type sourceType = source.GetType();
    Type targetType = target.GetType();
    // ensure that the types can be assigned to one another
    //if (!targetType.IsAssignableFrom(sourceType)) return;

    // loop through the properties of the source system
    foreach (PropertyInfo sourceMember in sourceType.GetProperties().Where(sourceMember => sourceMember.GetCustomAttribute(typeof(NoInheritAttribute)) == null))
    {
        var targetMember = targetType.GetProperty(sourceMember.Name);
        // if the property doesn't exist in the target, let's get out
        if (targetMember == null) continue;

        // check if this property is a Collection
        bool isCollection = (sourceMember.PropertyType.IsGenericType && sourceMember.PropertyType.GetInterfaces().Any(x =>
                                      x.IsGenericType &&
                                      x.GetGenericTypeDefinition() == typeof(IEnumerable<>)));

        // if we are not dealing with associations, let's get outta herre
        if (!(isCollection
                  ? sourceMember.PropertyType.GetGenericArguments().Single()
                  : sourceMember.PropertyType)
                 .IsSubclassOf(typeof(Association))) continue;

        if (isCollection)
        {
            IEnumerable<Association> targetCollection = (IEnumerable<Association>) targetMember.GetValue(target);
            // Loop through the collection and evaluate
            foreach (Association sourceAssociation in (IEnumerable) sourceMember.GetValue(source))
            {
                Association targetAssociation =
                    targetCollection.SingleOrDefault(t => t.AssociationId == sourceAssociation.AssociationId);
                CopyAssociation(sourceAssociation, targetAssociation);
            }
        }
        else
        {
            Association sourceAssociation = (Association) sourceMember.GetValue(source);
            Association targetAssociation = (Association) targetMember.GetValue(target);
            CopyAssociation(sourceAssociation, targetAssociation);
        }
    }
}

The problem is: It does not seem to be traversing the child objects properly and does not update the target as I would have expected. Looking for input and suggections as I am not as proficient in Reflection as I would like.

UPDATE: 12/06/2012

Ok, So I believe I’ve found the problem but still looking for a solution. This problem came to me from another dev on my team with the assumption that the object model was sound. However, it seems that the entity that we are currently testing does not retrieve the seeded values from the db.

There is nothing defined in the OnModelCreating() method defining this association although the tables are being properly created from the entity model and the data is being loaded properly from the dbSeed() method. I can run a select statement from the db and get the proper data. It seems that the entity model foreign key associations might be invalid and thus preventing the correct data retrieval. Any help would be greatly appreciated.

UPDATE: Ok, finally retrieving the correct data. This finally did it.

    modelBuilder.Entity<ClassSubjectivityAssoc>()
                .HasRequired(c => c.ClassCode)
                .WithMany(u => u.Subjectivities)
                .HasForeignKey(f => f.ClassCodeId);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T13:10:30+00:00Added an answer on June 15, 2026 at 1:10 pm

    See original post “UPDATES” for solution.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I use reflection find all the Classes in my project that Inherit from Packet.Base
In WPF, how do I use reflection to find all classes in a project?
How can I use reflection on an interface/abstract class to get all of its
The title pretty much says it all. When I'm doing some reflection through my
In my MVC application, I'm registering all of my controllers using reflection in the
I'm trying to use reflection to automatically test that all my linq2sql entities match
We have huge codebase and some classes are often used via reflection all over
Ok, I'm trying to use reflection to iterate through a class to get all
I am trying to use reflection to get all the (settable) properties in my
Is there a way to use .NET reflection to capture the values of all

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.