2017-04-15 91 views
1

如何查询基于ASP.NET的服务器中的SingleResult对象?请帮助下面的代码。如何查询基于ASP.NET的服务器中的SingleResult对象?

public class UserController : TableController<User> 
{ 
... 

public Task DeleteUser(string id) 
{ 
    SingleResult<User> user = Lookup(id); 
    // I can drill down into user via the debugger and see the data 
    // I'm looking for. But I don't know how to translate what I see 
    // in the debugger to a .Net call. 

    // This is what I see in the debugger: 
    // new System.Linq.SystemCore_EnumerableDebugView 
    // <AlertMeService.DataObjects.User>(result.Queryable).Items[0].GroupNm 
    // which equals "fooGrp" 

    // The below call doesn't work 
    // string GroupNm = user.GroupNm; 

    // I need GroupNm from the object to send a group notification 
    PostNotification(user.GroupNm, ...); 
    return DeleteAsync(id); 
} 
... 

任何帮助,非常感谢。

+0

我只想从查找返回的SingleResult对象中获取user.GroupNm。我不知道如何对它进行类型化。 – Mike

+0

你是否遵循了以下建议来检查这个问题,有没有更新? –

+0

布鲁斯,戴的下面的建议工作。感谢您的跟踪。 -Mike – Mike

回答

4

SingleResult返回IQueryable,因此请使用Linq SingleSingleOrDefault方法执行查询并获取结果。

Single将返回一个异常,如果返回0,2或更多的值,并且SingleOrDefault将允许0或1的值,并且如果返回2或多个值则会抛出。如果需要多个值,则使用First/FirstOrDefaultLast/LastOrDefault,或其他一些终端LINQ的方法,适当

SingleResult<User> userQuery = Lookup(id); 
User user = userQuery.SingleOrDefault(); 
if(user == null) { 

} 
else { 

} 
0

根据你的描述,我检查了SingleResult类:

public sealed class SingleResult<T> : SingleResult 
{ 
    // 
    // Summary: 
    //  Initializes a new instance of the System.Web.Http.SingleResult`1 class. 
    // 
    // Parameters: 
    // queryable: 
    //  The System.Linq.IQueryable`1 containing zero or one entities. 
    public SingleResult(IQueryable<T> queryable); 

    // 
    // Summary: 
    //  The System.Linq.IQueryable`1 containing zero or one entities. 
    public IQueryable<T> Queryable { get; } 
} 

根据我的理解,你可以修改你的方法如下:

public Task DeleteUser(string id) 
{ 
    SingleResult<User> result = Lookup(id); 
    var user=result.Queryable.SingleOrDefault(); 
    if(user!=null) 
    { 
     //I need GroupNm from the object to send a group notification 
     PostNotification(user.GroupNm, ...); 
     return DeleteAsync(id); 
    } 
    return Task.FromException($"the specific user with userid:{id} is not found."); 
}