2017-10-04 73 views
0

我需要創建一種通用的方法,將缺少的語言條目添加到實現特定接口的所有實體中。我發現如何獲得我的收藏屬性,但我仍然不知道如何在繼續保存之前在其上添加新值。通過實體導航屬性集合添加新條目

繼我的一塊public override int SaveChanges()處理。

foreach (var translationEntity in ChangeTracker.Entries(<ITranslation>)) 
{ 
    if (translationEntity.State == EntityState.Added) 
    { 
     var translationEntries = translationEntity.Entity.GetType() 
           .GetProperties(BindingFlags.Public | BindingFlags.Instance) 
           .Where(x => x.CanWrite && 
           x.GetGetMethod().IsVirtual && 
           x.PropertyType.IsGenericType == true && 
           typeof(IEnumerable<ILanguage>).IsAssignableFrom(x.PropertyType) == true); 

     foreach (var translationEntry in translationEntries) 
     { 
      //Add missing items. 
     } 
    } 
} 

類代碼樣本

public partial class FileType : ITranslation 
{ 
    public long FileTypeId { get; set; } 
    public string AcceptType { get; set; } 

    public virtual ICollection<FileTypeTranslation> FileTypeTranslations { get; set; } 

    public FileType() 
    { 
     this.FileTypeTranslations = new HashSet<FileTypeTranslation>(); 
    } 
} 

public class FileTypeTranslation : EntityTranslation<long, FileType>, ILanguage 
{ 
    [Required] 
    public string TypeName { get; set; } 
} 


public partial class ElementType : ITranslation 
{ 
    public long ElementTypeId { get; set; } 
    public string Code { get; set; } 

    public virtual ICollection<ElementTypeTranslation> ElementTypeTranslations { get; set; } 

    public ElementType() 
    { 
     this.ElementTypeTranslations = new HashSet<FileTypeTranslation>(); 
    } 
} 

public class ElementTypeTranslation : EntityTranslation<long, ElementType>, ILanguage 
{ 
    [Required] 
    public string Description { get; set; } 
} 
+0

你能告訴我更多嗎?什麼不起作用?如何添加新翻譯的代碼看起來像? –

+0

@KrzysztofSkowronek只是想象你有一個模型與一些集合屬性,並且你想從你的ChangeTracker修改這個集合。請考慮這個系列有一個已知的結構。 –

+0

好的,但是上面的代碼中沒有工作?我明白,你調用base.SaveCahnges作爲你的覆蓋方法的最後一件事,所以它應該做你想做的。這個集合是IT翻譯界面的一部分嗎?或者這是IT翻譯對象的集合? –

回答

1

從ChangeTracker條目有屬性稱爲實體持有原始實體

foreach (var fileType in ChangeTracker.Entries(<FileType>)) 
{ 
    fileType.Entity.FileTypeTranslations.Add(); 
} 

和的ElementType:

foreach (var elementType in ChangeTracker.Entries(<ElementType>)) 
{ 
    elementType.Entity.ElementTypeTranslations.Add(); 
} 

我沒有測試,但在評論中粘貼時間太長。

+0

這就是要點,但我不想逐一處理可能有收藏的實體。這就是爲什麼我通過Interface獲得它們,然後嘗試獲得肯定會存在的集合。我使用反射來達到這個目的,但我不知道如何在這個強類型的例子中找到這個對象上找到的集合屬性。 –

+0

恐怕那是不可能的。您必須運行相當複雜的refrection搜索才能找到所有類型爲ICollection 的屬性。我建議你用更簡短的方式去定義ITranslationContainer或ITranslatable,正如我在我的評論中所述,並使FileType和ElementType實現它。然後,只需瀏覽所有ChangeTracker.Entries

相關問題