我有实体'Reserve','ReservesUsers'和默认的'ApplicationUser'。
public class Reserve
{
public int ID { get; set; }
public string Begin { get; set; }
public string End { get; set; }
public string Date { get; set; }
public string Status { get; set; } //free , reserved, confirmed, canceled
public DateTime LastUpdate { get; set; }
public ICollection<ReserveUser> ReservesUsers { get; set; }
}
public class ReserveUser
{
[Key]
public int Id { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
public int ReserveId { get; set; }
[ForeignKey("ReserveId")]
public Reserve Reserve { get; set; }
}
public class ApplicationUser : IdentityUser
{
public bool IsProfessional { get; set; }
public ICollection<ReserveUser> ReservesUsers { get; set; }
}
由于我需要视图中的用户和保留,我明白了:
var usersByReserve = _context.Reserves
.Where(m => m.ID == id)
.Include(ru => ru.ReservesUsers)
.ThenInclude(ap => ap.User)
.ToList();
如何将其发送到视图并进行访问。
我试过了:
return View(usersByReserve);
并没有奏效。
处理请求时发生未处理的异常。
InvalidOperationException:传递给ViewDataDictionary的模型项的类型为'System.Collections.Generic.List`1 [Reservation.Models.Reserve]',但此ViewDataDictionary实例需要类型为'Reservation.Models.Reserve的模型项”。 EnsureCompatible
答案 0 :(得分:1)
您当前的代码会将@Component({
selector: 'my-app',
template: '<h2>Hello <example [config]="exampleConfig"></example></h2>'
})
export class App {
constructor() {
this.exampleConfig = new ExampleConfig();
this.exampleConfig.name = 'World';
}
protected exampleConfig: ExampleConfig;
}
@NgModule({
imports: [BrowserModule, ExampleModule],
declarations: [App],
bootstrap: [App]
})
export class AppModule {}
类对象(与您的where子句匹配)的集合返回给视图。但您的观点期待一个Reserve类的实例。即使你的where子句是条件导致单个记录,它仍将返回一个项的集合,因为Reserve
方法返回一个集合。
由于您正在查找单个项目(与您的where子句条件匹配),因此您可以使用Where
方法来获取该项目。
FirstOrDefault
现在,您需要将视图强类型化为Reserve类,然后您可以根据需要访问属性。
var usersByReserve = _context.Reserves
.Where(m => m.ID == id)
.Include(ru => ru.ReservesUsers)
.ThenInclude(ap => ap.User)
.FirstOrDefault();
if(usersByReserve !=null)
{
return View(usersByReserve);
}
else
{
//return a "not found message/view"
return Content("No item found for the id passed");
}