我正在尝试使用 MVC 和实体框架创建资产跟踪系统。数据库已经存在。我有一个带有 Location 字段的 ComputerInventory 表,它是 Location 表的 LocationID 的伪造键。我想要做的是当我输出有关库存的信息时,我不必查看 LocationID,我想查看对应 LocationID 的 Location 字段。
我一直在使用一些 tutproials,但我似乎无法更改它以适应我的需求。我认为这很常见,所以也许我遗漏了一些东西。这是我的计算机清单:
[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 模型还是必须从视图中访问位置?