how can I use Moles to redirect select from tables via LINQ?

最后都变了- 提交于 2019-12-22 10:49:57

问题


I have a table called Subscriptions. I'd like to redirect any LINQ select from that table to a Moles lambda so that only 3 rows are returned from that table -- basically I want to bypass the call to the database. So far, the code I have looks like this:

// lazy loader is here to handle successive calls to the 
// same table (otherwise there's an error)
// CM is a namespace alias
Table<CM.Subscriptions> subsTable = null;
MTheDataContext.AllInstances.SubscriptionsGet = (c) =>
    {
        if (subsTable == null)
        {
            subsTable = c.GetTable<CM.Subscriptions>();
            subsTable.Attach(new CM.Subscriptions() { SubID = 1, 
                 StatusCode = 1, CustomerID = custID1 });
            subsTable.Attach(new CM.Subscriptions() { SubID = 2, 
                 StatusCode = 1, CustomerID = custID2 });
            subsTable.Attach(new CM.Subscriptions() { SubID = 3, 
                 StatusCode = 4, CustomerID = custID3 });
            //  c.Refresh(RefreshMode.KeepCurrentValues, t);
        }
        return subsTable;
    };

Unfortunately it doesn't work. I've got about 1000 rows in the Subscriptions table in the database. When I run some test code that has this redirect in it, I get the 1000 rows from the database instead of the 3 rows that are in the redirect method. Clearly I'm missing something. What can I do to return only these 3 rows whenever any test code selects from the Subscriptions? I've got 3 calls to 3 different tables and they all need to select data that isn't in the db to get this test to work.

Clarification: the call to the redirected method does happen when I do a from sub in dc.Subscriptions ... select. But the rows returned aren't the rows that are in the redirect.


回答1:


Looks like I was doing this completely wrong. This is the correct approach:

// using System.Data.Linq.Moles; 
// CM is a namespace alias 
var subsList = new List<CM.Subscription>{
  new CM.Subscription() { SubscriptionID = subId1 },
  new CM.Subscription() { SubscriptionID = subId2 },
  new CM.Subscription() { SubscriptionID = subId3 }};

var subsTable = new MTable<CM.Subscription>();

subsTable.Bind(subsList.AsQueryable());

MTheDataContext.AllInstances.SubscriptionGet = (c) => { return subsTable; };

With this code, any selection from the Subscriptions table will return these three records only.



来源:https://stackoverflow.com/questions/4485502/how-can-i-use-moles-to-redirect-select-from-tables-via-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!