簡體   English   中英

.net core C#在EF Core Database首先生成的模型類上使用動態屬性名稱

[英].net core C# use dynamic property name on EF Core Database first generated model 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; }
    }

我正在寫一個更新方法:

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");
            }

我可以在JavaScript中做類似dynamic屬性的事情嗎? 例如

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

更新資料

截至2019年! 嘗試使用此新功能怎么樣? DynamicObject DynamicObject.TrySetMember(SetMemberBinder,Object)方法

我試圖弄清楚怎么寫。

您可以通過反射來實現對象上存在的屬性。

C#具有一個稱為Indexers的功能。 您可以像這樣擴展代碼,以實現您期望的行為。

 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); 
          }
       }
    }

除此之外,如果您在運行時不知道屬性,則可以使用動態類型。

如果您不想使用反射,則可以稍微調整Alens解決方案以使用字典存儲數據。

public class UserDetails
{
    private Dictionary<string, object> Items { get; } = new Dictionary<string, object>();

    public object this[string propertyName]
    {
        get => Items.TryGetValue(propertyName, out object obj) ? obj : null;
        set => Items[propertyName] = value;
    }

    public int? Level
    {
        get => (int?)this["Level"];
        set => this["Level"] = value;
    }
}

最接近的是ExpandoObject:

https://docs.microsoft.com/zh-cn/dotnet/api/system.dynamic.expandoobject?view=netframework-4.8

例如:

dynamic sampleObject = new ExpandoObject();
sampleObject.test = "Dynamic Property";
Console.WriteLine(sampleObject.test);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM