Adding new entries over entity navigation property collection

喜欢而已 提交于 2020-01-30 12:16:06

问题


I need to create a generic way to add missing languages entries to all entities in which implements an specific interface. I found out how to get my collection property, but I still don't know how to add new values on it before proceed to save.

Following a piece of my public override int SaveChanges() handling.

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.
        }
    }
}

Classes code samples

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

回答1:


Entries from ChangeTracker have property called Entity which holds original entity

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

and for ElementType:

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

I didn't test, but it was too long to paste in comment.



来源:https://stackoverflow.com/questions/46567964/adding-new-entries-over-entity-navigation-property-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!