私は通常、SQL と SSRS を使用しており、C# は初めてで、最初の MVC プロジェクトに取り組んでいます。
私の目的は、親とそれに関連付けられた子レコードを含むテーブルを表示するページを作成することでした-親が子の値ごとに繰り返されることはありません。
親テーブルのColumn1主キー
列 2 親テーブルの名前
列3 子の名前のリスト
これを達成するために、モデル ビューを作成しようとしました。
コードの配置に関連して多くの間違いを犯したと思います
モデル ビュー
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace SupplierItemTest.Models
{
public class VM_Trade
{
[Required]
[Display(Name = "Tax Info")]
public virtual string TaxpayerID { get; set; }
[Required]
[Display(Name = "Entity Name")]
public virtual string Supplier { get; set; }
[Required]
[Display(Name = "Trading Names")]
public virtual string SupplierTradingName1 { get; set; }
[Required]
[Display(Name = "Supplier Number")]
public virtual string EhSupplierNumber { get; set; }
}
}
コントローラ ビュー
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SupplierItemTest.Models;
namespace SupplierItemTest.Controllers
{
public class TradingNameController : Controller
{
private SupplierItemEntities db = new SupplierItemEntities();
//
// GET: /TradingName/
public ActionResult Index()
{
var Trade_View =
from s in db.Suppliers
join st in db.SupplierTradingNames on s.TaxpayerID equals st.TaxpayerID
join sn in db.EhSuppliers on s.TaxpayerID equals sn.TaxpayerID
orderby s.TaxpayerID
select new VM_Trade
{
SupplierTradingName1 = st.SupplierTradingName1,
TaxpayerID = s.TaxpayerID,
Supplier = s.SupplierName,
EhSupplierNumber = sn.EhSupplierNumber
};
return View(Trade_View.ToList());
意見
@model IEnumerable<SupplierItemTest.Models.VM_Trade>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.TaxpayerID)
</th>
<th>
@Html.DisplayNameFor(model => model.Supplier)
</th>
<th>
@Html.DisplayNameFor(model => model.EhSupplierNumber)
</th>
<th>
@Html.DisplayNameFor(model => model.SupplierTradingName1)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TaxpayerID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Supplier)
</td>
<td>
@Html.DisplayFor(modelItem => item.EhSupplierNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.SupplierTradingName1)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
- 最初に、View Model に IEnumerable を配置しようとしましたが、コントローラーの LINQ は次の結果を返しました
エラー「タイプ 'string' を 'Systen.Collections.Generic.IEnumerable に暗黙的に変換できません
私は誰かが私に言うことができることを望んでいました:
- モデルビューとコントローラの構造が間違っている場合
- 親列の単一の値を返す方法
私が読んだことから、私は次の非常に間違っています:
- モデル ビューでは IEnumerable を使用する必要があります
- データベース内の関係であるため、LINQ は結合を使用しないでください。
- ビューに IEnumerable を含めないでください
- 親列から単一の値を返し、子行に複数の値を返す方法がわかりません。
私は数日間読んでいますが、何でもうまくいくようです。