none
How do I apply polymorphism to two stored procedures to remove code duplication? RRS feed

  • Question

  • The two stored procedures called GetThings and GetThingsForActivity take the same parameters (in the same order, etc) and each return one result set, having the same columns in the same order.

    In the example code, db refers to the LinqToSql data context.

    public IEnumerable<ThingsGridItem> GetThingsGrid(ThingsSearch s)
    {
        if (s.ActivityID == 0)
        {
    	var Things = db.GetThings(s.UserLoginID, s.SortColumn, s.SortDirection, s.PageNumber, s.PageSize, s.ActivityID);
    	return Things.Select(c => new ThingsGridItem
    	{
    	    ThingID = c.ThingID,
    	    Thing = c.Thing,
    	    HistoricalThings = c.HistoricalThings,
    	    DerivedCount = (c.DerivedCount.HasValue) ? c.DerivedCount.Value : 0,
    	    TotalRows = (c.TotalRows.HasValue) ? c.TotalRows.Value : 0
    	});
        }
        else
        {
    	var Things2 = db.GetThingsForActivity(s.UserLoginID, s.SortColumn, s.SortDirection, s.PageNumber, s.PageSize, s.ActivityID);
    	return Things2.Select(c => new ThingsGridItem
    	{
    	    ThingID = c.ThingID,
    	    Thing = c.Thing,
    	    HistoricalThings = c.HistoricalThings,
    	    DerivedCount = (c.DerivedCount.HasValue) ? c.DerivedCount.Value : 0,
    	    TotalRows = (c.TotalRows.HasValue) ? c.TotalRows.Value : 0
    	});
        }
    }
    

    Note:
    var Things is of type ISingleResult<GetThingsResult>
    var Things2 is of type ISingleResult<GetThingsForActivityResult>

    Friday, June 22, 2012 4:40 PM

Answers

  • Hi Mark Pawelek,

    Welcome to MSDN Forum.

    Please refer to the steps below.

    1. Open .designer.cs file under the .dbml file.

    2. Looking for the two stored procedures and modify their return type to 'Things'.

    3. Modify the code as below.

    public IEnumerable<ThingsGridItem> GetThingsGrid(ThingsSearch s)
    {
        if (s.ActivityID == 0)
        {
    	List<Things> Things = db.GetThings(s.UserLoginID, s.SortColumn, s.SortDirection, s.PageNumber, s.PageSize, s.ActivityID).ToList();
    	return getThingsGridItem(Things);
        }
        else
        {
    	List<Things> Things2 = db.GetThingsForActivity(s.UserLoginID, s.SortColumn, s.SortDirection, s.PageNumber, s.PageSize, s.ActivityID);
    	return getThingsGridItem(Things2);
        }
    }
    
    public List<ThingsGridItem> getThingsGridItem(List<Things> list)
    {
    	return list.Select(c => new ThingsGridItem
    	{
    	    ThingID = c.ThingID,
    	    Thing = c.Thing,
    	    HistoricalThings = c.HistoricalThings,
    	    DerivedCount = (c.DerivedCount.HasValue) ? c.DerivedCount.Value : 0,
    	    TotalRows = (c.TotalRows.HasValue) ? c.TotalRows.Value : 0
    	}).ToList();
    }

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Monday, June 25, 2012 5:19 AM
    Moderator