实体框架6:添加到子集合

时间:2015-09-29 15:44:43

标签: entity-framework ef-code-first entity-framework-6

我首先使用的是EF6代码。我有一个父实体(Expense),它有子实体(Tag)的集合。实体是

 public class Expense : Entity
{
    //public Expense()
    //{
    //    this.Tags = new HashSet<Tag>();
    //}
    public string Title { get; set; }
    public ICollection<Tag> Tags { get; set; }

    //public long TagId { get; set; }
    public decimal Amount { get; set; }

    public long ByUserId { get; set; }
    public User ByUser { get; set; }

    public long? ForUserId { get; set; }
    public User ForUser { get; set; }

    public DateTime ExpenseDate { get; set; }
}

 public class Tag : Entity
{
    public Tag()
    {
        this.Expenses = new HashSet<Expense>();
    }
    public string Name { get; set; }

    public virtual ICollection<Expense> Expenses { get; set; }

    public long OrganizationId { get; set; }

    public Organization Organization { get; set; }
}

配置为

 public ExpenseConfiguration()
    {
        this.HasRequired(x => x.ByUser)
            .WithMany()
            .HasForeignKey(x => x.ByUserId)
            .WillCascadeOnDelete(false);

        this.HasOptional(x => x.ForUser)
            .WithMany()
            .HasForeignKey(x => x.ForUserId)
            .WillCascadeOnDelete(false);

        this.HasMany(x => x.Tags)
            .WithMany(t => t.Expenses)
            .Map(et => { 
                et.MapLeftKey("ExpenseId");
                et.MapRightKey("TagId");
                et.ToTable("tblExpenseTags");
            });
    }

 public TagConfiguration()
    {
        this.HasRequired(x => x.Organization)
            .WithMany()
            .HasForeignKey(p => p.OrganizationId)
            .WillCascadeOnDelete(false);
    }

我保存实体的方式

var tags = new List<Tag>();
        foreach (var item in expense.Tags)
        {
            var tag = _TagHandler.Get().Where(x => x.Id == item.Id).FirstOrDefault();
            tags.Add(tag);
        }

        entity.Tags.Clear();
        foreach (var item in tags)
        {
            expense.Tags.Add(item);
        }

if (expense.Id == 0)
        {
            entity.CreatedDate = DateTime.UtcNow;
            entity.UpdatedDate = DateTime.UtcNow;
            updated = EntityRepository.Add(entity);
        }
        else
        {
            expense.UpdatedDate = DateTime.UtcNow;
            updated = EntityRepository.Update(entity);
        }
        UnitOfWork.Commit();

当我创建费用时,我添加了多个标签并将其成功保存在tblExpenseTags中,但问题是当我向Expense添加新标签时,他们没有保存到tblExpenseTags表中。我使用sql profiler来查看SQL数据库的调用,并且在更新费用时我没有看到任何插入调用。

请让我知道我做错了什么?

0 个答案:

没有答案