如何查询导航属性代码优先MVC4

时间:2013-10-05 06:59:45

标签: sql entity-framework asp.net-mvc-4 code-first

这里有什么问题?我在产品和交易之间有很多对。尝试构建view,但我无法获得任何智能感知查询加载ProductTransaction表。

实体1

     [Table("Transactions")]
public class Transaction
{
        [Key]
        public virtual int TID { get; set; }

        public virtual int FromUserID { get; set; }
        public virtual int ToUserId { get; set; }
        public virtual int itemForId { get; set; }

        public virtual ICollection<Product> Products { get; set; }

}

实体2

      [Table("Products")]
public class Product
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public virtual int ProductId { get; set; }

    [Required]
    [StringLength(50, ErrorMessage="Name can't be longer than 50 characters bitch")]
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }

    public virtual DateTime? UploadDate { get; set; }

    public virtual byte[] ProductImage { get; set; }
    [StringLength(25)]
    public virtual string MimeType { get; set; }

    public virtual int Views { get; set; }

    public virtual int Qty { get; set; }

    // Relations
    public virtual UserProfile User { get; set; }
    public virtual int UserId { get; set; }
    public virtual int CategoryId { get; set; }

    public virtual ICollection<Bag> Bags { get; set; }
    public virtual ICollection<Transaction> Transactions{ get; set; }
}

控制器方法查看所有交易和交易:查询没有Products的智能感知

     public ViewResult GetTrades()
    {
        //Include is not recognizing any nav properties

        var friend = db.Transactions.Include(a => a.Products);

    }

多对多的关系

       modelBuilder.Entity<Transaction>()
            .HasMany(p => p.Products)
            .WithMany(t => t.Transactions)
            .Map(m =>
                {
                    m.ToTable("ProductTransactions");
                    m.MapLeftKey("ProductId");
                    m.MapRightKey("TID");


                });

1 个答案:

答案 0 :(得分:0)

DbExtensions.Include(this IQueryable, Expression<Func<T, TProp>>)是一种扩展方法。

您需要包含命名空间以作为扩展方法访问它。

using System.Data.Entity;