从链接表中检索数据并将其显示在视图中

时间:2018-02-26 14:42:45

标签: c# asp.net model-view-controller

我有两个型号:

M1:

namespace wb01.Models
{
    using System;
    using System.Collections.Generic;

    public partial class M1
    {
        public M1()
        {
            this.M2 = new HashSet<M2>();
        }

        public int Id { get; set; }
        public int N° { get; set; }
        public string Commentaires { get; set; }
        public int Id_qualité { get; set; }

        public virtual Qualité Qualité { get; set; } //*(Qualité est autre table dans ma BDD)


        public virtual ICollection<M2> M2 { get; set; }
    }
}

第二个模型M2:

namespace wb01.Models
{
    using System;
    using System.Collections.Generic;

    public partial class M2
    {
        public int Id_M2 { get; set; }
        public string N_wg { get; set; }
        public double Poids { get; set; }

        public int Id { get; set; }

        public virtual M1 M1 { get; set; }
    }
}

和控制器:

namespace wb01.Controllers
{
    using static wb01.Models.M2;

    public class M1Controller : Controller
    {
        private M1Entities db = new M1Entities();

        // GET: M1
        public ActionResult Index()
        { 
            var m1 = db.M1.Include(r => r.Qualité);
            return View(m1.ToList()); 
        }
    }
}

我想在我的视图中显示m1.ToList,其中一列包含M1中每个Id的Poid(M1中的m1_ID表示其Poids = sum(poids mi_ID in M2)。如果有人可以,请帮帮我?

2 个答案:

答案 0 :(得分:0)

所以也许你可以尝试加入你的2个表:

public ActionResult Index()
{
    var query = db.M1    // your starting point - table in the "from" statement
        .Join(db.M2, // the source table of the inner join
        t1 => t1.id,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
        t2 => t2.id,   // Select the foreign key (the second part of the "on" clause)
        (t1, t2) => new { t1 = t1, t2 = t2 }) // selection
        .Where(M1AndM2 => M1AndM2.t1.id == 1);    // where statement

    return View(m1.ToList());
}

答案 1 :(得分:0)

您可以按需投影所需的列

var m1 = db.M1.Include(r => r.M2).Include(r => r.Qualité).Select(r => new {
    Poids = r.M2.Sum(x => x.Poids),
    Col1 = r.Col1,
    Col2 = r.Col2,
    Col3 = r.Col3,
    Col4 = r.Col4
});
return View(m1.ToList());