简体   繁体   English

SQL Server查询创建不同的返回类型

[英]SQL Server query creating different return types

I'll go straight with the code, then explain my problem, this way it will be easier. 我将直接处理代码,然后解释我的问题,这样会更容易。 Just to give a heads up, I use entity framework 7 with SQL Server 2014, ASP.NET 5 and MVC 6. 提醒一下,我将实体框架7与SQL Server 2014,ASP.NET 5和MVC 6一起使用。

So, I've following classes : 因此,我上了以下课程:

public class Base {
    public int BaseId { get; set; }
    public string Name { get; set; }
}
public class DerivedOne : Base { 
    public virtual List<OtherDBObject> ListOne { get; set; }  
}
public class DerivedTwo : Base {
    public string SomeContent { get; set; }
}

And I created repository that retrievs Base objects from database. 我创建了一个存储库,用于从数据库中检索基础对象。 Problem is, DerivedOne and DerivedTwo have different members - how can I know which type to return (which members to query further)? 问题是,DerivedOne和DerivedTwo具有不同的成员-我如何知道要返回哪种类型(进一步查询哪些成员)?

public class Repo : IRepo {
    public async Task<Base> GetById(int id) {
        // I though that this method should work something like this (its pseudo code) :
        context.Base.Where(b => b.BaseId == id)
            .switch(obj.type) {
                case DerivedOne : query for OtherDBObjects
                case DerivedTwo : query for string content somewhere else
                ...
            }).First();
    }
}

My goal is to have very abstract Base class containing just a few basic fields and derived ones can be completely diffrent. 我的目标是拥有仅包含几个基本字段的抽象类,而派生类可以完全不同。

PS If you have different structure for this task, feel free to post it! PS:如果您为此任务使用不同的结构,请随时发布!

You can write good stuff by using generics and extensions methods, something like the following: 您可以使用泛型和扩展方法来编写好东西,如下所示:

public static Task<TEntity> GetByIdAsync<TEntity>( 
    this DbSet<TEntity> set, int id)  where TEntity : Base
{
    return set.FirstOrDefaultAsync(e => e.Id == id);
}

Sample usage: 用法示例:

DerivedOne entity = await DbContext.DerivedOnes.GetByIdAsync(id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM