本文介绍了实体框架1到许多脚手架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

数据库表:区域,肌肉

区域是人类的一个区域身体(例如胸部)
肌肉是人体上的肌肉(例如三角肌)

A Region is a region on the human body (e.g. Chest)A Muscle is a muscle on the human body (e.g. Deltoids)

肌肉具有RegoinId作为ForeignKey。

A Muscle has a RegoinId as foreignKey.

以下是模型类别:

public class Region
{
    [Key]
    public int RegionId { get; set; }
    public string RegionName { get; set; }
    public virtual ICollection<Muscle> Muscles { get; set; }
}

    public class Muscle
{
    [Key]
    public int MuscleId { get; set; }
    public string LatinName { get; set; }
    public string DkName { get; set; }
    public string EnName { get; set; }
    public string Description { get; set; }
    public int RegionId { get; set; }
    public Region Region { get; set; }
}

然后我用以下方法搭建了RegionsController:

I then scaffolded a RegionsController with the following method:

// GET: api/Regions
    public IQueryable<Region> GetRegions()
    {
        return db.Regions;
    }

这很好,但是该地区的Muscles属性为空。

This works fine, but the Muscles property of the region is null.

所以我能以某种方式告诉Entity Framework在搭建控制器类时自动包含区域肌肉吗?

So can i somehow tell Entity Framework to automatically include a regions muscles, when scaffolding the controller class?

梦太多了,我该如何吸收自己的肌肉?

If that is too much dreaming, how can i then include the muscles myself?

我没有运气就尝试了以下方法:

I tried the following without luck:

var regions = db.Regions.ForEachAsync(r => r.Muscles = db.Muscles.Where(m => m.RegionId == r.RegionId));

抱怨,因为r.Muscles是ICollection,而db.Muscles是IQueryable类型。

Complaining since r.Muscles is an ICollection and db.Muscles is of type IQueryable.

所以,请问我有哪些选择和最佳做法来使自己的区域具有相应的肌肉。

So please, what are my options and best practises for getting out my regions with their corresponding muscles.

(如果这意味着解决方案有什么用,我的最终目标是为我的angularJS应用返回json)

(if it means anything to the solution, my end goal is to return json for my angularJS app)

谨记程序员,:

推荐答案

查询区域时,还包括肌肉

return db.Regions.Include(s=>s.Muscles)

方法包括查询结果中include子句中指定的相关对象。

Include method include the related objects specified in the include clause in the query results.

这篇关于实体框架1到许多脚手架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-10 20:55