【发布时间】:2017-10-04 14:52:58
【问题描述】:
我需要创建一种通用方法,将缺失的语言条目添加到实现特定接口的所有实体中。我找到了如何获取我的收藏属性,但我仍然不知道如何在其上添加新值继续保存。
按照我的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; }
}
【问题讨论】:
-
你能告诉更多吗?什么不工作?添加新翻译实体的代码是什么样的?
-
@KrzysztofSkowronek 想象一下你有一个具有一些集合属性的模型,并且你想从你的 ChangeTracker 中修改这个集合。请同时考虑此集合具有已知结构。
-
好的,但是上面的代码有什么问题?我知道你调用 base.SaveCahnges 作为你覆盖方法中的最后一件事,所以它应该做你想做的事。这个集合是 ITranslation 接口的一部分吗?还是这个 ITranslation 对象的集合?
-
上面的代码只是返回集合属性,但是我不能通过添加或删除任何东西来修改它——我没有这些方法。我也尝试使用
translationEntity.Collection("MyCollectionName");,但我也没有添加或删除方法。不,该集合不是 ITranslation 的一部分。 -
那么您必须获取所有具有翻译属性的条目并修改其集合。您代码中的方法只会获取所有添加的翻译。你必须找到所有的父母