我想從模型中選擇特定的列,但在嘗試爲子實體包含select時出錯。我的模型是 -在asp.net中的lambda表達式MVC
public class Alert
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid AlertId { get; set; }
[Display(Name = "Title"), MaxLength(160, ErrorMessage ="Title cannot be more than 200 characters long."), Required(ErrorMessage ="You must enter an alert title")]
// [DataType(DataType.MultilineText)]
public string Title { get; set; }
[Display(Name = "Description"), MaxLength(8000, ErrorMessage = "Title cannot be more than 8000 characters long."), Required(ErrorMessage ="You must enter a description in {0} field")]
[AllowHtml]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Start Date"), Required(ErrorMessage ="You must enter the start date and time")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm tt}", ApplyFormatInEditMode = false)]
// [DataType(DataType.DateTime)]
public DateTime StartDate { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm tt}", ApplyFormatInEditMode = false)]
[Display(Name = "End Date")]
public DateTime? EndDate { get; set; }
[Display(Name = "Affected Site/s"), MaxLength(200,ErrorMessage ="You cannot enter more than 200 characters.")]
public string SitesAffected { get; set; }
[MaxLength(10)]
public string Published { get; set; }
[Display(Name = "Website Link"), MaxLength(200,ErrorMessage ="This cannot be more than 200 characters.")]
public string WebLink { get; set; }
[Display(Name ="Alert Type")]
public int AId { get; set; }
public virtual ICollection<Location> Location { get; set; }
public virtual ICollection<AlertFile> Files { get; set; }
[JsonIgnore]
public virtual AlertType alertType {get; set;}
}
我可以使用以下lambda表達式通過Web API生成json數據。
var alerts = db.Alerts.Where(a=>a.alertType.Slug== alert && a.EndDate>=DateTime.Now && a.Published=="Yes").Select(s=>new
{s.Title, s.Description, s.alertType.Slug, s.StartDate, s.EndDate, s.Location
});
return Request.CreateResponse(HttpStatusCode.OK, alerts.ToList());
上述代碼顯示位置表中的所有列。我想顯示位置表中的特定列,我嘗試了下面的代碼,但得到錯誤。
var alerts = db.Alerts.Where(a=>a.alertType.Slug== alert && a.EndDate>=DateTime.Now && a.Published=="Yes").Select(s=>new
{s.Title, s.Description, s.alertType.Slug, s.StartDate, s.EndDate, s.Location.Select(l => new Location { l.Name, l.Latitude, l.Longitude, l.ParkId, l.Contact })
});
Error: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
基本上位置不允許我使用SELECT子句。任何人都可以請幫忙。提前致謝。
你得到的錯誤是什麼? –
'匿名類型成員聲明符無效。匿名類型成員必須使用成員賦值,簡單名稱或成員訪問來聲明。' – Tajuddin
'locations = s.Location.Select(l => new {l.Name,l.Latitude,...})' –