c# - 无法使用实体框架核心映射实体
问题描述
我在数据库中有两个表:产品,供应商我希望实体框架定义每个产品的供应商我成功获取两个表的数据,但产品表中的供应商为空。此外,供应商表中的产品集合为空。这是我的产品类别:
public class Product
{
public int id { get; set; }
[Column("Productname", TypeName = "ntext")]
public string Name { get; set; }
public decimal UnitPrice { get; set; }
public bool isDiscounted { get; set; }
public int quantity { get; set; }
public int SupplierId { get; set; }
[ForeignKey("SupplierId")]
public Supplier supplier { get; set; }
}
这是供应商的类别:
public class Supplier
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string city { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string Fax { get; set; }
public List<Product> Products { get; set; }
}
上下文类:
public class DbConext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbConext(DbContextOptions<DbConext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().ToTable("Product");
modelBuilder.Entity<Supplier>().ToTable("Supplier");
modelBuilder.Entity<Product>().HasKey("id");
modelBuilder.Entity<Supplier>().HasKey("Id");
modelBuilder.Entity<Product>().HasOne(p => p.supplier).WithMany(s => s.Products).HasForeignKey(p => p.SupplierId);
}
}
解决方案
这篇文章可能会有所帮助。
您应该使用.Include()
加载任何相关属性。
推荐阅读
- sql - MSSQL WHERE YEAR 子句返回所有日期而不是指定日期
- asp.net - 通过vb.net中的foreach循环在列表中插入类属性
- python - 用整数规划求解最小化
- sql - hibernate如何登录哪部分代码导致了给定的SQL
- javascript - 反应用户引用不向字段添加焦点状态
- json - 数据帧到 JSON 的转换
- gitlab-ci - 如何在 GitLab 管道中运行安全代码扫描?
- c++ - 如何使用模板类在 C++ 中正确进行多重继承?
- c# - ASP.NET Core web.config 位置使用
- vue.js - 通过 axios 发出 Post 请求时将 HttpListenerContext.User 设为 null