我有一个使用此控制器填充的列表视图:
public ActionResult ListClubMembershipType(int clubId)
{
//Populate the list
var types = from s in db.MembershipTypes
where (s.ClubId == clubId)
orderby s.Type
select s;
ViewBag.typesCount = types.Count();
var model = types.Select(t => new ListMembershipTypeViewModel
{
Type = t.Type,
ClubId = clubId,
Cost = t.Cost,
ReducedCost = t.ReducedCost,
MinAge = t.MinAge,
MaxAge = t.MaxAge,
});
return PartialView("_ListClubMembershipType", model);
}
我还想在名为ReducedDate的视图模型中填充一个变量,其中包含从其他两个表中提取的数据,Day&一个月。
我尝过以下几行:
ReducedDate = db.Days.Find(t.DayId).DayNum + "/" + db.Months.Find(t.MonthId).MonthName,
但它会出现以下错误:
其他信息:方法' GRCWebApp.Models.Day Find(System.Object [])'声明类型' System.Data.Entity.DbSet1 [GRCWebApp.Models.Day]'无法使用类型&System; System.Data.Entity.Core.Objects.ObjectQuery1 [GRCWebApp.Models.Day]'
的实例调用引用数据的正确方法是什么?
模型是:
MembershipType
public int MembershipTypeId { get; set; }
[StringLength(150)]
[Column(TypeName = "nvarchar")]
public String Type { get; set; }
[StringLength(350)]
[Column(TypeName = "nvarchar")]
public String Description { get; set; }
[Column(TypeName = "int")]
public int ClubId { get; set; }
[Column(TypeName = "decimal")]
public Decimal Cost { get; set; }
[Column(TypeName = "decimal")]
public Decimal ReducedCost { get; set; }
[Column(TypeName = "int")]
public int? DayId { get; set; }
[Column(TypeName = "int")]
public int? MonthId { get; set; }
[Column(TypeName = "int")]
public int MinAge { get; set; }
[Column(TypeName = "int")]
public int MaxAge { get; set; }
[Column(TypeName = "bit")]
public bool? Dormant { get; set; }
}
日模型:
public class Day
{
public int DayId { get; set; }
[Column(TypeName = "int")]
public int DayNum { get; set; }
public virtual ICollection<MembershipType> MembershipTypes { get; set; }
}
月份模型:
public class Month
{
public int MonthId { get; set; }
[Column(TypeName = "nvarchar")]
public String MonthName { get; set; }
public virtual ICollection<MembershipType> MembershipTypes { get; set; }
}
ViewModel是:
public class ListMembershipTypeViewModel
{
[Display(Name = "Type")]
public String Type { get; set; }
public int ClubId { get; set; }
[Display(Name = "Full Cost")]
public Decimal Cost { get; set; }
[Display(Name = "Reduced Cost")]
public Decimal ReducedCost { get; set; }
[Display(Name = "Reduced From")]
public string ReducedDate { get; set; }
[Display(Name = "Min Age")]
public int MinAge { get; set; }
[Display(Name = "Max Age")]
public int MaxAge { get; set; }
}
答案 0 :(得分:1)
DayId
上有MonthId
和MembershipType
,但您不具备public Day Day {get;set;}
和public Month Month {get;set;}
如果你有这些属性,你可以使用ReducedDate = t.Day.DayNum + "/" + t.Month.MonthName
这可能会给您一个错误,因为DayNum
是一个整数,因此您需要将DayNum
转换为string
。您可以使用SqlFunctions.StringConvert((double)t.Day.DayNum)
执行此操作。