访问dbset子类型的扩展方法

时间:2014-07-26 15:22:05

标签: methods dbset

我有一个扩展方法定义为:

public static class CurrentItemExtensions
{
    static GPOPricingEntities ctx = new GPOPricingEntities();

    public static List<CurrentItem> Get(this DbSet<CurrentItem> item, int tierId, string contractId)
    {
        List<CurrentItem> items = ctx.Items.OfType<CurrentItem>().Where(x => x.TierId == tierId).ToList();

        if (items == null)
        {
            GPOPricing.AS400Models.ItemCollection collection = new GPOPricing.AS400Models.ItemCollection().Get(contractId);

            foreach (var c in collection)
            {
                CurrentItem target = new CurrentItem();
                target.Price = c.DirectPriceEaches;
                target.SKU = c.LongItemNbr;
                target.Description = c.Description;
                target.ProductLine = c.ProductLine;

                items.Add(target);
            }
        }
        else
        {
            foreach (var i in items)
            {
                GPOPricing.AS400Models.Item as400Item = new GPOPricing.AS400Models.ItemCollection().GetBySKU(i.SKU);
                i.Description = as400Item.Description;
                i.ProductLine = as400Item.ProductLine;
            }
        }
        return items;
    }
}

我遇到的问题是访问它 - CurrentItem是Item的子类型。所以我试过了:

 db.Items.Get (doesn't work)

我试过

 db.Items.OfType<CurrentItem>().Get (doesn't work)

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我发现我必须使用基类型并为每个子类型创建一个方法:

public static class CurrentItemExtensions
{
    static GPOPricingEntities ctx = new GPOPricingEntities();

    public static List<CurrentItem> GetCurrentItems(this DbSet<Item> item, int tierId, string contractId)
    {
        List<CurrentItem> items = ctx.Items.OfType<CurrentItem>().Where(x => x.TierId == tierId).ToList();

        if (items.Count() == 0)
        {
            GPOPricing.AS400Models.ItemCollection collection = new GPOPricing.AS400Models.ItemCollection().Get(contractId);

            foreach (var c in collection)
            {
                CurrentItem target = new CurrentItem();
                target.Price = c.DirectPriceEaches;
                target.SKU = c.LongItemNbr;

                items.Add(target);
            }
        }
        else
        {
            foreach (var i in items)
            {
                GPOPricing.AS400Models.Item as400Item = new GPOPricing.AS400Models.ItemCollection().GetBySKU(i.SKU);
            }
        }
        return items;
    }
}