Sharepoint 2010 listitem to linq 2 sharepoint spmetal class

846 views Asked by At

How can I wrap/convert/cast a ListItem to the generated spmetal class ? (linq 2 sharepoint)

Thanks!

Update:

I'm looking for these because event receivers make use of splistitems and i want to use the strong type version and no magiv strings when accessing data

1

There are 1 answers

1
Josh On

Is there a reason you have a ListItem instead of using LINQ to SharePoint to get your spmetal class?

To my knowledge there is no built in way but you could use a tool like automapper to do this.

Mapper.CreateMap<SPListItem, HandbookCodesHandbookCode>()
            .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.ID))
            .ForMember(dest => dest.CodeDescription, opt => opt.MapFrom(src => src["CodeDescription"]));
        SPWeb web = SPContext.Current.Site.RootWeb;
        SPList list = web.Lists["HandbookCodes"];

        SPListItem item = list.GetItemById(1);

        HandbookCodesHandbookCode hc = Mapper.Map<SPListItem, HandbookCodesHandbookCode>(item);

Another way of doing this would be to use LINQ to SharePoint and just create a query to get this like

HandbookTeamSiteDataContext ctx = new HandbookTeamSiteDataContext(SPContext.Current.Site.RootWeb.Url);

        var hb = from h in ctx.HandbookCodes
                 where h.Id == 1
                 select h;

Unless you are given a SPListItem (Event Receiver and workflows) I would try to use this instead of getting a SPListItem (Unless you have a complex query that doesn't perform well then)