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

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

问题描述

好了,我有一个产品叫做抽象类。我有3个表称为项目,工具包,以及实现产品软件包。产品具有一个公开对象的主键的公共属性。



这是说我在那里我通过产品的形式。我想拉该产品出了新鲜的DataContext,而无需编写一个大的switch反映它的类型来获得其应有的表。



我要像做。这一点,但剧组位将不接受富

 公共BuilderInclusionsForm(产品p):这个()
{
类型为foo = p.GetType();
产物= db2.GetTable(p.GetType())演员所述。foo的方式>()的SingleOrDefault(一个= GT;
a.ProductID == p.ProductID);

或这样的:

 公共BuilderInclusionsForm(产品p):这个()
{
类型为foo = p.GetType();
产物= db2.GetTable(p.GetType())OfType&所述。foo的方式>()的SingleOrDefault(一个= GT;
a.ProductID == p.ProductID);


解决方案

与感谢飞碟双向先生的美好会员我。团队指出了以下解决方案

 公共BuilderInclusionsForm(产品p):这个()
{
IEnumerable的<产品与GT; 。PS = db2.GetTable(p.GetType())演员LT;产品>();
产品= ps.SingleOrDefault(A => a.ProductID == p.ProductID);
}



对不起,浪费你的时间。请不要垃圾收集我对不起屁股约翰。 = OD


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.

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);

or this:

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

解决方案

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);
}

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

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

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