MVC と Entity Framework を使用して資産追跡システムを作成しようとしています。データベースは既に存在します。Location テーブルの LocationID への偽造キーである Location のフィールドを持つ ComputerInventory テーブルがあります。私がやろうとしているのは、在庫に関する情報を出力するときです。LocationID を見る必要はありません。対応する LocationID の Location フィールドを見たいのです。
いくつかの tutproials を使用していますが、自分のニーズに合わせて変更できないようです。これはかなり一般的だと思うので、何かが足りないのかもしれません。これが私のComputerInventoryです:
[Table("ComputerInventory")]
public class ComputerInventory
{
[Key]
public String AssetTag {get; set;}
//public Int32 Location { get; set; }
[ForeignKey("Location")]
public virtual Location Location { get; set; }
public Int32 PoolType { get; set; }
public Int32 Reason { get; set; }
public Int32 InventoryStatus { get; set; }
public Int32 InventoryType { get; set; }
[StringLength(500)]
public String Comments { get; set; }
//public String Clock { get; set; }
// public ICollection<Location> Locations { get; set; }
}
public class AssetDBContext : DbContext
{
public DbSet<ComputerInventory> ComputerInventory { get; set; }
public AssetDBContext()
: base("Name=LaptopLoaner_RW")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ComputerInventory>().HasRequired(l => l.Location).WithMany();
}
}
これが私のロケーションモデルです
[Table("Location")]
public class Location
{
[Key]
public Int32 Id { get; set; }
//[Column(LocationName="LocationName")]
[MaxLength(100)]
public String LocationName { get; set; }
[MaxLength(25)]
public String Country { get; set; }
}
public class LocationDBContext : DbContext
{
public DbSet<Location> Locations { get; set; }
public LocationDBContext()
: base("Name=<name>")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
ビューにデータを出力しようとしている場所は次のとおりです。
@model IEnumerable<LaptopLoaner.Models.ComputerInventory>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.AssetTag)
</td>
<td>
@Html.DisplayFor(modelItem => item.InventoryStatus)
</td>
<td>
@Html.DisplayFor(modelItem => item.Location.LocationName)
</td>
<td>
@Html.DisplayFor(modelItem => item.PoolType)
</td>
<td>
@Html.DisplayFor(modelItem => item.Reason)
</td>
<td>
@Html.DisplayFor(modelItem => item.InventoryType)
</td>
<td>
@Html.DisplayFor(modelItem => item.Comments)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AssetTag }) |
@Html.ActionLink("Details", "Details", new { id=item.AssetTag }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AssetTag })
</td>
</tr>
}
ComputerInventory モデルを変更する必要がありますか、それともビューから場所にアクセスする必要がありますか?