Обновление значений свойств сущности посредством отражения - PullRequest
0 голосов
/ 10 июля 2020

У меня есть структура класса сущности, подобная этой, как показано ниже, с json столбцами, которые связаны с классами, и я в процессе обновления сущности некоторыми значениями.

[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "ORM", Scope = "module")]
public class DesignProject : PatchEntityProperties
{
    [Key, GraphQLNonNullType]
    public string ProjectNumber { get; set; }
    public string Name { get; set; }
    [Column(TypeName = "jsonb")]
    public ProjectSectionStatus SectionStatuses { get; set; } = new ProjectSectionStatus();
}

, а затем Класс ProjectSectionStatus выглядит следующим образом:

public class ProjectSectionStatus
{
    public Guid Id { get; set; } = Guid.NewGuid();
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage ExecutiveSummarySectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage CodesAndGuidelinesSectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    public string CodesAndGuidelinesSectionNotesHTML { get; set; } = "";
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage AirSystemsSectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    public string AirSystemsSectionNotesHTML { get; set; } = "";
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public ProjectSectionStage ExhaustEquipmentSectionStatus { get; set; } = ProjectSectionStage.NOT_STARTED;
    public string ExhaustEquipmentSectionNotesHTML { get; set; } = "";
    ....
    .....
    .....
}

. Ниже я обновляю некоторые свойства в статусах разделов для targetdesignproject

 var targetDesignProject = this._dbContext.DesignProjects.Where(a => a.ProjectNumber == targetProjectNumber).SingleOrDefault();
 targetDesignProject.SectionStatuses.AirSystemsSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.CodesAndGuidelinesSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.ExecutiveSummarySectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.ExhaustEquipmentSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
 targetDesignProject.SectionStatuses.InfiltrationSectionStatus = Entities.Enums.ProjectSectionStage.INCOMPLETE;
        ......
        ......

есть 10 или более похожих свойств статуса, которые мне нужны для обновления одного за другим со статусом перечисления INCOMPLETE, поэтому я попытался использовать метод отражения, чтобы обновить все сразу, но застрял при установке значения

 PropertyInfo[] properties = targetDesignProject.SectionStatuses.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            
 foreach (PropertyInfo property in properties)
 {
    var propValue = property.GetValue(targetDesignProject.SectionStatuses);

    if (propValue is ProjectSectionStage)
    {
       property.SetValue() // not sure how to update here 
    }
 }

Есть ли способ обновить эти статусы с помощью отражения со статусом перечисления Incomplete. Может ли кто-нибудь сообщить нам идею в предложениях, как обновить их с помощью отражения, который был бы очень мне благодарен.

заранее спасибо

Обновление:

foreach (PropertyInfo property in properties)
{
     var propValue = property.GetValue(targetDesignProject.SectionStatuses);

     if (propValue is ProjectSectionStage)
     {
           property.SetValue(targetDesignProject, ProjectSectionStage.INCOMPLETE, null); 
           // getting an error - Object does not match target type
      }
 }

Ответы [ 2 ]

0 голосов
/ 10 июля 2020

Вы можете сделать

PropertyInfo[] properties = targetDesignProject.SectionStatuses.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            
 foreach (PropertyInfo property in properties)
 {
    var propValue = property.GetValue(targetDesignProject.SectionStatuses);

    if (propValue is ProjectSectionStage)
    {
       property.SetValue(targetDesignProject.SectionStatuses, propValue)

       // You can do this if you want
       // var newPropValue = rojectSectionStage.INCOMPLETE;
       // property.SetValue(targetDesignProject.SectionStatuses, newPropValue)
    }
 }

Кроме того, вы можете обратиться к этой странице, если вам нужна дополнительная документация:

https://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view=netcore-3.1

https://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view=netcore-3.1#System_Reflection_PropertyInfo_SetValue_System_Object_System_Object_System_Object__ _

0 голосов
/ 10 июля 2020

Я решил эту проблему с помощью кода ниже

foreach (PropertyInfo property in properties)
{
     var propValue = property.GetValue(targetDesignProject.SectionStatuses);

     if (propValue is ProjectSectionStage)
     {
           property.SetValue(targetDesignProject.SectionStatuses, ProjectSectionStage.INCOMPLETE, null); 
           // getting an error - Object does not match target type
      }
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...