-1

在 c# Entity Framework 4 或 5 中

实体类#1

public class ClassOne
{
   public string FirstName { get;set; }
}

public class ClassTwo : ClassOne
{
    public string LastName get;set; }
}

对于 IQueryable:

return from e in Context.pClassOneList from r in SomeOtherList select new ClassTwo
{

    // right here how do I get all the fields assigned without having to do it manually? ie:
    FirstName = e.FirstName,



    LastName = r.SomeOtherVar // works perfectly, but the whole of ClassOne is not assigned unless I do it manually.
}

谢谢你的帮助。

4

2 回答 2

0

简而言之,在表达式中自动绑定基类属性的唯一方法是动态生成 select 表达式。这将是相当多的工作,并且会减慢您的代码速度。我不认为这是要走的路。然而,也许你可以简单地封装它而不是扩展基类——你可以将结果嵌入到另一个对象中,如下所示:

public class ResultType 
{
    public ClassOne ClassOne { get; set; }
    public string SomeOtherVar { get; set; }
}

return  
    from e in Context.pClassOneList 
    from r in SomeOtherList 
    select new ResultType
    {
        ClassOne = e,
        SomeOtherVar = r.SomeOtherVar
    };
于 2013-08-20T18:41:03.017 回答
0

好的,所以你基本上是在获取两个不同的列表,然后使用对象初始化器实例化一个新对象,所以你当然必须手动完成。

您可以在 ClassTwo 中创建一个构造函数,它采用 ClassOne 并结合 ClassTwo 的继承属性,甚至使用适配器模式来处理它。

SomeOtherList 可能必须“手动”处理,具体取决于它包含的内容。但是,当您开始对构造函数进行创意时,请注意您的 SOLID 原则。

于 2013-08-20T18:47:25.020 回答