asp.net-core - 如何在 EF Core 上创建自定义导航属性

标签 asp.net-core many-to-many entity-framework-core

我正在使用.NET Core 2.0。我写了很多导航属性,我知道目前 EF Core 上不支持自动延迟加载。我正在使用 Microsoft 方法来创建导航属性。我正在尝试创建多对多关系。

首先创建手动映射表,该表也像新的 DbSet 一样包含在 ApplicationDbContext 中

public class ProductCategory
    {
        [Key]
        public int ProductId { get; set; }
        [ForeignKey("ProductId")]
        public virtual Product Product { get; set; }

        [Key]
        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public virtual Category Category { get; set; }
    }

   public class Product
    {
        public int Id { get; set; }
        public virtual ICollection<ProductCategory> ProductCategory { get; set; 
    }

   public class Category
    {
        public int Id { get; set; }
        public virtual ICollection<ProductCategory> ProductCategory { get; set; 
    }

在 OnModelCreating 类中

            builder.Entity<ProductCategory>()
            .HasKey(x => new { x.CategoryId, x.ProductId });

            builder.Entity<ProductCategory>()
                .HasOne(x => x.Product)
                .WithMany(x => x.ProductCategory)
            .HasForeignKey(x => x.ProductId);

            builder.Entity<ProductCategory>()
               .HasOne(x => x.Category)
               .WithMany(x => x.ProductCategory)
            .HasForeignKey(x => x.CategoryId);

在映射表中添加新对象时。

var productCategory = new ProductCategory
            {
                CategoryId = 1,
                ProductId = 1
            };

            db.ProductCategory.Add(productCategory);
            db.SaveChanges();

项目添加成功,之后尝试访问产品或类别来测试导航属性,但仅接收映射表中的当前类。您可以看到我尝试从类别类访问产品时的示例:

model.Categories = this._categoryService
                .All()
                .Include(x => x.ProductCategory)
                .ToList();

many-to-many-error-ef7

产品类别为空?

最佳答案

这是因为包含导航属性会自动包含反向导航属性,仅此而已。您需要使用 ThenInclude 特别询问。 .

假设All方法返回 IQueryable<Category> ,像这样:

model.Categories = this._categoryService
                .All()
                .Include(x => x.ProductCategory)
                    .ThenInclude(x => x.Product)
                .ToList();

请注意,这还将自动包含(加载)ProductCategory Product的集合属性实体。

关于asp.net-core - 如何在 EF Core 上创建自定义导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46488150/

相关文章:

c# - 自托管 ASp.net core 2.2 应用程序,未找到 View 'Index'。搜索了以下位置

c# - .NET Core Entity Framework 存储过程

ruby - 多对多 : how to prevent duplicates? 上的 Rails 嵌套表单

SQL:保证恰好 N 行与多对多查询匹配?

c# - 如何使用 Entity Framework `ValueComparer<T>` ?

c# - 强制 ASP.NET Core Entity Framework Core 中的继承类到专用 MySQL 表

c# - 在 Docker 镜像中使用 ASP.Net Core 时应用 Entity Framework 迁移

asp.net - 如何从 JwtSecurityTokenHandler 获取日志输出?

visual-studio - 尝试从 Docker 中的 VS 运行时出现错误 "getcwd() failed: No such file or directory"

postgresql - 一个 INSERT 多个 SELECT