Jordec
Jordec

Reputation: 1562

C# AmbiguousMatchException when GetProperty and trying to map two objects with eachother

I'm trying to make a function that maps a eUsers list object to a user list object. It will actually map a few properties, but when propertyInfo.Name == "UserName", it'll throw me a AmbiguousMatchException on the following line:

typeof(User)
    .GetProperty(ePropertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField)
    .SetValue(user, ePropertyInfo.GetValue(currentEUser));

I tested and it seems it being triggered by the GetProperty method. I'm not really sure what could cause this. Here is the full function:

private List<User> ConvertEUsersToUsers(List<eUser> eUsers)
{
    List<User> users = new List<User>();
    User user = null;

    IList<PropertyInfo> eUserProps = new List<PropertyInfo>(eUsers.FirstOrDefault().GetType().GetProperties());
    IList<PropertyInfo> userProps = typeof(User).GetProperties();
    foreach (eUser currentEUser in eUsers)
    {
        user = new User();
        foreach (PropertyInfo ePropertyInfo in eUserProps)
        {
            foreach (PropertyInfo propertyInfo in userProps)
            {
                if (propertyInfo.Name == ePropertyInfo.Name)
                {
                    if (ePropertyInfo.CanWrite)
                    {
                        typeof(User)
                            .GetProperty(ePropertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField)
                            .SetValue(user, ePropertyInfo.GetValue(currentEUser));
                    }
                    break;
                }
            }
        }
        users.Add(user);
    }
    return users;
}

EDIT:

Here is a part of the User and eUser class:

[Serializable]
[Application(7)]
[Table("Users")]
public partial class User : MembershipUser, IPrincipal, IIdentity, IEntity, IIdNameClass {

    [Column("Name")]
    public new EntityField UserName { get; set; }
}

[Table("Users")]
public class eUser : User
{
    [NotMapped]
    public Boolean selected { get; set; }

    public new UserTypes UserType { get; set; }

    public eUser() : base()
    {
        selected = false;
    }
}

Upvotes: 0

Views: 407

Answers (1)

odyss-jii
odyss-jii

Reputation: 2729

You are shadowing a property called UserName in one of your base classes by using the new keyword when declaring UserName on your User class. This means that there is in fact more than one property called UserName: the original one from one of the base classes, and the new one in User. This is what causes the AmbiguousMatchException.

Try using the BindingFlags.DeclaredOnly flag to only fetch properties declared on the type in question: User.

Upvotes: 5

Related Questions