开发者

linq casting to object

开发者 https://www.devze.com 2023-02-04 07:52 出处:网络
I have a linq query as follow: public static ViewUserDisplayPreferences GetUserDisplayPreferences(int TheUserID)

I have a linq query as follow:

public static ViewUserDisplayPreferences GetUserDisplayPreferences(int TheUserID)
{

    using ( MyDataContext TheDC = new MyDataContext() )
    {

        var OutputUserDisplayPreferences = from user in TheDC.Users
                                    where user.UserID == TheUserID
                                    select new ViewUserDisplayPreferences
                                    {
                                        UserTimeFormat = user.UserTim开发者_JS百科eDisplay
                                    };

        return (ViewUserDisplayPreferences)(OutputUserDisplayPreferences);
    }
}

For the moment, the object ViewUserDisplayPreferences is defined as follow (more variables will be added later):

public class ViewUserDisplayPreferences
{
public string UserTimeFormat { get; set; }
};

On the return statement at runtime, I get this error:

Unable to cast object of type 'System.Data.Linq.DataQuery`1[ObjectsUsers.ViewUserDisplayPreferences]' to type 'ObjectsUsers.ViewUserDisplayPreferences'.]

What's wrong with the code? The intellisense is not showing any error on the line?

Thanks


OutputUserDisplayPreferences is an IEnumerable<T>. If you want an object, use either the First (if there can be more than one) or Single (if you know for sure only one object will be in the sequence) method on the sequence. If it is possible for the sequence to be empty, use the respective *OrDefault method.


Linq returns a collection. Try adding a .FirstOrDefault to the end.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号