Eagerloading多对多相关数据

时间:2016-12-01 01:54:29

标签: c# sql-server asp.net-mvc entity-framework-core

我正在使用Entity框架核心。 我在ComponentType和Category

之间有多对多的关系

ComponentType模型:

// specify an "as" value and require a User.project_id value
Project.hasMany(User, { as: 'Users', foreignKey: { allowNull: false } });

// define your Project -> Users as json with the "as" value as the key
const project = {
  name: 'project name',
  Users: [
    {
      name: 'user 1',
    },
    {
      name: 'user 2',
    },
  ],
};

// create a transaction and "include" the Model in the create, txn falls back in .catch()
sequelize.transaction(t => 
  Project.create(project, {
    include: [{
      model: User,
      as: 'Users',
    }],
    transaction: t,
  })
)
.catch(e => console.log('the txn failed because', e));

类别模型

using System.Collections.Generic;


namespace embeddedstock.Models
{
    public class ComponentType
    {
        public ComponentType()
        {
            Components = new List<Component>();
            CategoryComponentType = new List<CategoryComponentType>();
        }
        public long ComponentTypeId { get; set; }
        public string ComponentName { get; set; }
        public string ComponentInfo { get; set; }
        public string Location { get; set; }
        public ComponentTypeStatus Status { get; set; }
        public string Datasheet { get; set; }
        public string ImageUrl { get; set; }
        public string Manufacturer { get; set; }
        public string WikiLink { get; set; }
        public string AdminComment { get; set; }
        public virtual ESImage Image { get; set; }
        public ICollection<Component> Components { get; protected set; }
        public ICollection<CategoryComponentType> CategoryComponentType { get; protected set; }

    }

 }

数据透视表/模型

using System.Collections.Generic;

namespace embeddedstock.Models
{
    public class Category
    {
        public Category()
        {
            CategoryComponentType = new List<CategoryComponentType>();
        }
        public int CategoryId { get; set; }
        public string Name { get; set; }
        public ICollection<CategoryComponentType> CategoryComponentType { get; protected set; }
    }
 }

数据库上下文

namespace embeddedstock.Models
{
    public class CategoryComponentType
    {
        public int CategoryId { get; set; }
        public Category Category { get; set; }

        public long ComponentTypeId { get; set; }
        public ComponentType ComponentType { get; set; }
    }
}

当我尝试这个时:

using embeddedstock.Models;
using Microsoft.EntityFrameworkCore;

namespace embeddedstock.Contexts
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions<DatabaseContext> options)
            :base(options) { }
        public DatabaseContext(){ }

        public DbSet<Component> Components { get; set; }

        public DbSet<ComponentType> ComponentTypes { get; set; }

        public DbSet<Category> Categories { get; set; }

        public DbSet<ESImage> ESImages { get; set; }

        public DbSet<CategoryComponentType> CategoryComponentTypes { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<CategoryComponentType>()
                .HasKey(t => new { t.CategoryId, t.ComponentTypeId });

            modelBuilder.Entity<CategoryComponentType>()
                .HasOne(cpt => cpt.Category)
                .WithMany(c => c.CategoryComponentType)
                .HasForeignKey(cpt => cpt.CategoryId);

            modelBuilder.Entity<CategoryComponentType>()
                .HasOne(cpt => cpt.ComponentType)
                .WithMany(ct => ct.CategoryComponentType)
                .HasForeignKey(cpt => cpt.ComponentTypeId);
        }

    }
}

它计算了相关数据的正确数量,但我得到了这个例外:

  

RuntimeBinderException:无法对空引用执行运行时绑定   CallSite.Target(Closure,CallSite,object)

与此方法相关的视图:当我获取没有任何关系的类别时,它可以正常工作。

public IActionResult Show(int id)
{
    var Cat = DbContext.Categories.Include(x => x.CategoryComponentType).FirstOrDefault(y => y.CategoryId == id);

    Console.WriteLine(Cat.CategoryComponentType.Count);


    ViewBag.Category = Cat;

    return View();
}

0 个答案:

没有答案