我正在研究Asp.Net Core应用程序。我有4个相关的表。
城市,街道,房屋和警报装置
该应用程序用于管理警报安装。
房屋属于街道和城市,它们是相关的。房子有一个DoorNr属性...
当我尝试创建新的警报安装时。它向我显示了我可以通过ID获得的房屋,但是我需要它来显示完整的地址。问题在于房屋类别仅具有StreetId(来自Street Class)和DoorNr。我如何设法显示完整的地址?
public partial class AlarmInstall
{
public int AlarmInstallId { get; set; }
public int HouseId { get; set; }
public string Model { get; set; }
public virtual House House { get; set; }
}
public partial class House
{
public House()
{
AlarmInstall = new HashSet<AlarmInstall>();
}
public int HouseId { get; set; }
public int StreetId { get; set; }
public string DoorNr { get; set; }
public int CityId { get; set; }
public virtual City City { get; set; }
public virtual Street Street { get; set; }
public virtual ICollection<AlarmInstall> AlarmInstall { get; set; }
}
public partial class Street
{
public Street()
{
House = new HashSet<House>();
}
public int StreetId { get; set; }
public string StreetName { get; set; }
public virtual ICollection<House> House { get; set; }
}
public partial class City
{
public City()
{
House = new HashSet<House>();
}
public int CityId { get; set; }
public string CityName { get; set; }
public virtual ICollection<House> House { get; set; }
}
我的AlarmsInstallController具有以下代码:
// GET: AlarmInstalls/Create
public IActionResult Create()
{
ViewData["HouseId"] = new SelectList(_context.House, "HouseId", "HouseId");
return View();
}
// POST: AlarmInstalls/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("AlarmInstallId,HouseId,Model")] AlarmInstall alarmInstall)
{
if (ModelState.IsValid)
{
_context.Add(alarmInstall);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["HouseId"] = new SelectList(_context.House, "HouseId", "DoorNr", alarmInstall.HouseId);
return View(alarmInstall);
}
我的视图具有以下代码:
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="HouseId" class="control-label"></label>
<select asp-for="HouseId" class ="form-control" asp-items="ViewBag.HouseId"></select>
</div>
这是我的HouseId的SelectList ...
ViewData["HouseId"] = new SelectList(_context.House, "HouseId", "HouseId");
我需要显示完整的地址,由streetName(来自StreetClass)和DoorNr组成,而不是HouseId,我应该在代码中进行哪些更改?
感谢您的提前帮助!
答案 0 :(得分:0)
在Google的帮助下自行解决...
public IActionResult Create()
{
// ViewData["HouseId"] = new SelectList(_context.House, "HouseId", "HouseId");
var fullAddress = _context.House
.Select(h => new { HouseId = h.HouseId, FullAddress = h.Street.StreetName
+ ", " + h.DoorNr })
.ToList();
ViewBag.HouseId = new SelectList(fullAddress, "HouseId", "FullAddress");