在实体导航属性集合上添加新条目 [英] Adding new entries over entity navigation property collection

查看:144
本文介绍了在实体导航属性集合上添加新条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一种通用方法,向所有实现特定接口的实体添加缺少的语言条目.我找到了如何获取我的收藏属性,但是我仍然不知道如何在此属性上添加新值,然后继续保存.

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.

按照我的public override int SaveChanges()的规定进行操作.

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

类代码示例

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

推荐答案

ChangeTracker中的条目具有名为Entity的属性,该属性保存原始实体

Entries from ChangeTracker have property called Entity which holds original entity

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

,对于ElementType:

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.

这篇关于在实体导航属性集合上添加新条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆