实体框架多对多关系加载子项

时间:2015-07-31 04:03:47

标签: entity-framework many-to-many entity-framework-6 code-first

我使用EF 6 Code-first来创建我的数据库。 我有两个实体费用和标签,它们之间存在很多关系。

public class Expense : Entity
{

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

和Tag Class是

 public class Tag : Entity
{
   public string Name { get; set; }

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

我使用EntityTypeConfiguration配置了实体,如

internal class ExpenseConfiguration : BaseEntityConfiguration<Expense>
{
    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");
            });
    }
}

internal class TagConfiguration : BaseEntityConfiguration<Tag>
{
    public TagConfiguration()
    {

    }
}
一切顺利。它使用新表&#34; tblExpenseTags&#34;正确创建数据库表。其中包含Expense和Tag的多对多关系。

问题出在加载时。

如果我使用

database.Entry(expense).Collection("Tags").Load();

它工作,即它加载标签,其中数据库是DbContext。

但是当我使用

dbSet.Where(x=>x.Id == 8).Include(x=>x.Tags);

它不起作用。我的假设是.Load()是否正常工作.Include也应该有用吗?

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

尝试将EXTRA_OUTPUT放在过滤谓词之前:

Include

...但是由于您要查询费用var expensesWithTags = dbSet.Include(x => x.Tags).Where(x => x.Id == 8); ,您可能希望改为使用IdSingle谓词:

SingleOrDefault
相关问题