如何将我的LINQ查询结果作为特定对象返回

Lee*_*Lee 0 c# linq-to-entities entity-framework-4 asp.net-mvc-3

如何将我的LINQ查询结果作为特定对象返回

public CountryTable GetSelectedEventInfo(string SelectedEventID)
{
    return (CountryTable) this.context.Event.Where(
                   e => e.EventID.Equals(Convert.ToInt32(SelectedEventID)));
}
Run Code Online (Sandbox Code Playgroud)

这是我的模特

public class CountryTable
{
    public int EventID { get; set; }
    public string Title { get; set; }
    public DateTime Startdate { get; set; }
    public DateTime EndDate { get; set; }
    public string EventUrl { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的数据库上下文

public DbSet<CountryTable> Event { get; set; }
Run Code Online (Sandbox Code Playgroud)

以下是我想要做的

public CountryTable GetSelectedEventInfo(string SelectedEventID)
{
    return (CountryTable) this.context.Event.Where(
                   e => e.EventID.Equals(Convert.ToInt32(SelectedEventID)));
}
Run Code Online (Sandbox Code Playgroud)

我需要我的查询结果返回CountryTable类型的对象

Dar*_*rov 5

你可以使用这个SingleOrDefault方法:

public CountryTable GetSelectedEventInfo(string SelectedEventID)
{
    int id = Convert.ToInt32(SelectedEventID);
    return this.context.Event.SingleOrDefault(e => e.EventID == id);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果在数据库中找不到匹配的记录,则此方法将返回null.