多态性和LinqToSql

时间:2012-02-27 10:38:00

标签: c# linq

我有两个应用程序。一个使用XAF(devexpress框架),第二个使用asp.net mvc。 我的bussines类是在XAF app中创建的。都使用相同的数据库。 我在XAF的课程:

    public class BaseClass:XPObject
    {
    // some fields
    }

    // This attribute mean that all fields will be stored in BaseClass table
    [MapInheritance(InheritanceType.ParentTable] 
    public class Class1:BaseClass
    {
    // some fields
    }

   // This attribute mean that all fields will be stored in BaseClass table
    [MapInheritance(InheritanceType.ParentTable] 
    public class Class2:BaseClass
    {
    // some fields
    }

在数据库中,我们有一个表格BaseClass,其中的字段来自BaseClassClass1

有这样的时刻:XAF添加了自己的字段ObjectType(它是FK到XPObjectType表,XAF自动创建)。 结果我们在DB中:

BaseClass:

ID      some_fields_from_BaseClass      some_fields_from_Class1      ObjectType
1             some_values                    some_values                1

XPObjectType:
ID                TypeName                    AssemblyName
1             TestApp.Module.BO.Class1       TestApp.Module 

现在,我在ASP.NET MVC应用程序中写道:

Database.BaseClasses.Where( ...some predicate...).ToList();

此查询返回BaseClass的集合。但是,我希望该查询返回我的派生类型(例如Class1Class2Class 3)。 我怎么能这样做?

PS。我不能使用IsDiscriminator属性,因为它是FK,我不想在asp.net mvc应用程序中删除对象(Class1class2。)

1 个答案:

答案 0 :(得分:2)

试试这个:

public List<T> GetData<T>(Func<T,bool> fn) where T :BaseClass
    {
        if (typeof(T) == typeof(BaseClass))
        {
            List<T> res = null; // Fillout from database
            var r = res.Where(fn).Select(o => (BaseClass)o).ToList();
        }
        else
        {
            throw new Exception("Invalid type, this service support only BaseClasses");
        }

        return null;
    }
相关问题