如何正确初始化 var 类型

How to properly initialize a var type

我有这段代码:

DatabaseContext dbContext = modul.CreateContext();

var returnvalue = dbContext.tbl_person
    .ToArray()
    .Select(item => new PersonGridRow
        {
            PersonID = item.PersonID,
            ...
        });

我需要让它更有活力,所以它使用相同的选择,但 table。

我想做这样的事情:

DatabaseContext dbContext = modul.CreateContext();
var selection;
if(some condition)
{
    selection = dbContext.tbl_person;
}
else
{
    selection = dbContext.tbl_personHistory
}

var returnvalue = selection
    .ToArray()
    .Select(item => new PersonGridRow
        {
            PersonID = item.PersonID,
            ...
        });

两个 table 是相同的。我知道 var 不是一种类型,而是执行时的一个数字,类型是什么。我也尝试过使用动态关键字,但没有成功。 我该如何解决?

您可以使用 conditional operator

var select = something == otherthing ? 
    dbContext.tbl_person.Select(item => new PersonGridRow
    {
        PersonID = item.PersonID,
        ...
    }) :
    dbContext.tbl_personHistory.Select(item => new PersonGridRow
    {
        PersonID = item.PersonID,
        ...
    });

其他技术包括在 EF 的模型浏览器中将 personHistory table 的基类型更改为与 person table 相同的实体。然后你就可以这样做了...

 var select = (
        something == otherthing ? 
            dbContext.tbl_person : 
            dbContext.tbl_personHistory
    ).Select(item => new PersonGridRow
    {
        PersonID = item.PersonID,
        ...
    });

另一种选择是分配所有共享属性并与之交互,然后将第一个 table 转换为 IQueryable<IPerson> 或“IEnumerable”

 var select = (
        something == otherthing ? 
            (IQueryable<IPerson>)dbContext.tbl_person : 
            dbContext.tbl_personHistory
    ).Select(item => new PersonGridRow
    {
        PersonID = item.PersonID,
        ...
    });

最后,您可以在服务器端创建一个视图,在 personpersonHistory 之间执行 union all,并使用此视图作为查询的基础。

创建一个接口来表示这些表共有的数据:

public interface IPerson
{
    int PersonID {get;}
    //...
}

然后让您正在使用的两个表的两种实体类型都实现该接口。完成后,您可以使用该接口声明变量:

DatabaseContext dbContext = modul.CreateContext();
IQueryable<IPerson> selection;
if(some condition)
    selection = dbContext.tbl_person;
else
    selection = dbContext.tbl_personHistory

var returnvalue = selection
    .Select(item => new PersonGridRow
        {
            PersonID = item.PersonID,
            ...
        });