c# - 如何将两个表中的数据返回到模型中?
问题描述
我有两个表(模型):
生产表:
Id
Name
Price
颜色表:
Id
ProduceId
Color
我想在产品上显示颜色。例如:
1. green-------- Produce1
2. Red ----------Produce1
3. green --------Produce2
我在存储库中的代码:
public IEnumerable<ColorsVM> GetColors()
{
var _query = _context.Colors_tbl.Include(c => c.Produces_tbl).Include(d => d.produceId).AsQueryable();
return _query;
}
我的模型:ColorsVM:
public class ColorsVM
{
public int Id { get; set; }
public int produceId { get; set; }
public string Color { get; set; }
public Produces Produces { get; set; }
}
但不工作。
解决方案
您应该映射produce
表的外键以便能够使用include
.
您可以通过Fluent API
或Data Annotations来完成。下面的示例使用Data Annotations。请参阅以下链接以获取更多说明。
public class Color
{
public int Id { get; set; }
public int produceId { get; set; }
public string Color { get; set; }
[ForeignKey("produceId ")]
public Produce Produce { get; set; }
}
推荐阅读
- android - 将密钥库和应用程序与具有多个应用程序的旧密钥库分开
- optaplanner - VRP 与团队建设
- python - 如何从 json 文件的依赖项中读取 python 工具并在 python 解包时安装它?
- c# - IIS Express Asp.Net 长 URL 返回 400 Bad Request
- wordpress - Wordpress 中的恶意代码(恶意重定向)
- c# - 如何在文本文件中写入格式化字符串
- python - 使用Python运行时如何改变视频的运行速度
- python - 获取DF中最大值的索引名称
- identityserver4 - 循环 ReturnUrlParsers 时的空引用
- jquery - 当我关闭所有组行时,DataTable 显示 0 条记录?