.net core C# use dynamic property name on EF Core Database first generated model class

.net-core c# entity-framework-core

Question

I have a user details class

public partial class UserDetails
    {
        public int? Level { get; set; }
        public string Unit { get; set; }
        public string Bio { get; set; }
        public bool? Gender { get; set; }
        public int? Mobile { get; set; }
        public string Photo { get; set; }
    }

I am writing an update method:

public bool UpdateDetails(string userId, UserProperties updateProperty, string value)
        {
         switch(updateProperty)
            {
                case UserProperties.Unit:
                    details.Unit = value;
                    break;
                case UserProperties.Photo:
                    details.Photo = value;
                    break;
                default:
                    throw new Exception("Unknown User Detail property");
            }

May I do something like dynamic property in JavaScript? e.g.

var details = new UserDetails();
details["Unit"] = value;

Update

As of year 2019! How about try to use this new feature?! DynamicObject DynamicObject.TrySetMember(SetMemberBinder, Object) Method

I am trying to figure out how to write it.

1
1
4/26/2019 2:14:53 PM

Popular Answer

You can do it via reflection for properties that exist on the object.

C# has a feature called Indexers. You could extend your code like this to allow for the behavior you are expecting.

 public partial class UserDetails
    {
        public int? Level { get; set; }
        public string Unit { get; set; }
        public string Bio { get; set; }
        public bool? Gender { get; set; }
        public int? Mobile { get; set; }
        public string Photo { get; set; }
         // Define the indexer to allow client code to use [] notation.
       public object this[string propertyName]
       {
          get { 
            PropertyInfo prop = this.GetType().GetProperty(propertyName);
            return prop.GetValue(this); 
          }
          set { 
            PropertyInfo prop = this.GetType().GetProperty(propertyName);
            prop.SetValue(this, value); 
          }
       }
    }

Other than that, if you don't know the properties at runtime, you can use the dynamic type.

3
4/26/2019 10:04:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow