C# 如何将两个表中的数据返回到模型中?

C# 如何将两个表中的数据返回到模型中?,c#,repository-pattern,C#,Repository Pattern,我有两张桌子(型号): 生产表: Id Name Price 颜色表: Id ProduceId Color 我想在屏幕上显示颜色。例如: 1. green-------- Produce1 2. Red ----------Produce1 3. green --------Produce2 存储库中的我的代码: public IEnumerable<ColorsVM> GetColors() { var _query = _conte

我有两张桌子(型号):

生产表:

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

但不起作用。

您应该映射
product
表的外键,以便能够使用
include
加载它

您可以通过
Fluent API
或。下面的示例使用的是数据注释。有关更多说明,请参见以下内容

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

错误CS0266无法将类型“System.Linq.IQueryable”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(是否缺少转换?)映射应在
模型
类中进行,而不是在
视图模型
类中进行。您的
Color
类(表)应该具有
product
属性,并且您可以映射您的
外键。
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; }
}