首页 > 解决方案 > 如何将两个表中的数据返回到模型中?

问题描述

我有两个表(模型):

生产表:

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; }
    }

但不工作。

标签: c#repository-pattern

解决方案


您应该映射produce表的外键以便能够使用include.

您可以通过Fluent APIData 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; }
}

推荐阅读