Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
LinqToSql Question
Message
General information
Forum:
ASP.NET
Category:
LINQ
Miscellaneous
Thread ID:
01486527
Message ID:
01486536
Views:
53
>I have this method:
>
>
>public MerchantModel GetMerchant(int MerchantID)
>{
>    MerchantModel retVal = null;
>
>    using (TDCDataDataContext dc = new TDCDataDataContext())
>    {
>        var merchants = (from m in dc.tblMerchants
>                            where m.RecordId == MerchantID
>                            select new MerchantModel
>                            {
>                                RecordId = m.RecordId,
>                                CategoryId = m.CategoryId,
>                                Title = m.Title,
>                                Icon = m.Icon,
>                                Slogan = m.Slogan,
>                                DateAdded = m.DateAdded,
>                                Rating = m.Rating.Value,
>                                WebSiteURL = m.WebSiteURL
>                            }).ToList();
>
>        retVal = merchants[0];
>    }
>
>    return retVal;
>}
>
>
>Do I have to use ToList to make this work? How do I query for just one Merchant and return the MerchantModel?
>

Since you're wrapping this in a using statement, yes, you'll have to use ToList(). Normally L2S (and EF) will build an expression tree from your query and delay running it until it's absolutely needed. Calling ToList() will force the query to be run. If you don't do that then the DataContext will be disposed of before the query is run (because of the using). Remove the using if you don't want that behavior.

The normal way to get a specific item in the list would be to use something like merchants.FirstOrDefault() which returns either the first item or a null if no items are found. Do this before the ToList().
-Paul

RCS Solutions, Inc.
Blog
Twitter
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform