使用抽象类型的反射从表中获取实体 [英] Get Entity From Table Using Reflection From Abstract Type

查看:14
本文介绍了使用抽象类型的反射从表中获取实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个名为 Product 的抽象类.我有 3 个表,称为 Items、Kits 和 Packages,它们实现了 Product.产品具有公开对象的主键的公共属性.

Ok, so I have an abstract class called Product. I have 3 tables called Items, Kits, and Packages that implement Product. Product has a public property that exposes the object's primary key.

也就是说我有一个表格,我可以在其中传递产品.我想将该产品从新的数据上下文中提取出来,而不必编写反映其类型的大开关来获取其正确的表.

That said I have a form where I pass a product. I would would like to pull that product out of a fresh datacontext without having to write a big switch reflecting it's type to get its proper table.

我想做这样的事情,但演员表不接受 foo.

I wanted to do something like this but the cast bit won't accept foo.

public BuilderInclusionsForm(Product p) : this()
        {            
            Type foo = p.GetType();
            product = db2.GetTable(p.GetType()).Cast<foo>().SingleOrDefault(a => 
                a.ProductID == p.ProductID);

或者这个:

public BuilderInclusionsForm(Product p) : this()
        {            
            Type foo = p.GetType();
            product = db2.GetTable(p.GetType()).OfType<foo>().SingleOrDefault(a => 
                a.ProductID == p.ProductID);   

推荐答案

感谢 Skeet 先生,我团队中一位聪明的成员指出了以下解决方案.

With thanks to Mr. Skeet a bright member of my team pointed out the following solution.

public BuilderInclusionsForm(Product p) : this()
{
    IEnumerable<Product> ps = db2.GetTable(p.GetType()).Cast<Product>();
    product = ps.SingleOrDefault(a => a.ProductID == p.ProductID);
}

很抱歉浪费您的时间.请不要垃圾收集我对不起的屁股约翰.=oD

Sorry to waste your time. Please don't garbage collect my sorry ass John. =oD

这篇关于使用抽象类型的反射从表中获取实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆