2017-06-03 20 views
1

我需要映射到其相應數據表的模型,並且每次更新模型/表時,都需要將更改映射到已存檔錶的歷史參考。例如 -C#中的MVC模型複製#

[Table("A")] 
public class A 
{ 
    [Key]  
    public int A_Id { get; set; }  

    [Display(Name = "First Name")] 
    public string FirstName { get; set; } 

    [Display(Name = "Last Name")] 
    public string LastName { get; set; } 
} 

[Table("A_History")] 
public class A_History 
{ 
    [Key] 
    public int A_History_Id { get; set; }  

    public int A_Id { get; set; }  

    [Display(Name = "First Name")] 
    public string FirstName { get; set; } 

    [Display(Name = "Last Name")] 
    public string LastName { get; set; } 
} 

所以每次表A被修改,我需要與新的或原始數據的精確副本添加到A_History一個條目。有沒有一種通用的方法來做到這一點,以便我可以將字符串作爲Model名稱傳遞給方法或類,並且該方法可以自動遍歷Model類的所有屬性,並將它們映射到另一個類以便通過匹配名稱添加?

+0

聽起來像你正在尋找的東西像Automapper ... –

+0

這可能是保存在不同的數據庫 – sniels

+0

我以前沒有使用過Automapper歷史數據是個好主意,但是從我讀,不是嗎」用於將ViewModel映射到Model?至於不同數據庫中的歷史數據,那會有什麼好處呢?你是否擔心數據規模會擴大到很大?速度? – Joe

回答

0

以下使用反射,所以要注意性能。如果性能是一個非常重要的方面,那麼實際上可以逐一映射屬性會更好,但是如果您正在尋找泛型實現,則可以嘗試下面的代碼片段。

// object instances 
A sourceInstance = new A(); 
A_History destInstance = new A_History(); 
MapSourceValuesToDestination(sourceInstance, destInstance); 

private void MapSourceValuesToDestination(object sourceObject, object destinationObject) 
{ 
    //get all properties 
    PropertyInfo[] sourceProperties = typeof (sourceObject).GetProperties(); 
    PropertyInfo[] destinationProperties = typeof (destinationObject).GetProperties(); 

    // foreach in source 
    foreach (PropertyInfo property in sourceProperties) 
    { 
     if (property != null) 
     { 
      string propertyName = property.Name; 
      if (!string.IsNullOrEmpty(propertyName)) 
      { 
       // get destination property matched by name 
       PropertyInfo matchingProperty = destinationProperties.FirstOrDefault(x => x.Name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase));  
       if (matchingProperty != null) 
       { 
        // get source value 
        object sourceValue = property.GetValue(sourceInstance); 
        if (sourceValue != null) 
        { 
         // set source value to destination 
         matchingProperty.SetValue(destInstance, sourceValue); 
        } 
       } 
      } 
     } 
    } 
} 
+0

謝謝你。當我有機會時,我將不得不嘗試一下。是的,我正在尋找一個通用的實現,因爲每個獲得更新的數據表都需要相應歷史記錄表的更新/存檔。 – Joe

+0

@Joe對此有何更新?這是否解決了你的問題? – touchofevil

+0

我還沒有嘗試過這種方法。我試過了自動映射器,它的工作原理很奇怪。我會在接下來的一週嘗試這種方法。一旦我嘗試一下,我會在下週發佈更新。我想知道它是否也能起作用。謝謝您的幫助。 – Joe

0

如果你的歷史模型具有相同的屬性作爲保持,那麼你可以這樣做歷史的模型。

  1. 添加Newtonsoft.Json nuget包並做。

  2. 添加下面顯示的代碼。

    A model = new A(); 
    //..... 
    // add data to the model 
    var json = JsonConvert.SerializeObject(model); 
    A_History historyModel = JsonConvert.DeserializeObject<A_History>(json); 
    
  3. 現在你的歷史模式將填補所有與該模型相同的屬性。