简体   繁体   中英

Can I achieve dynamic object with dynamic fields from db in ASP.NET C#

I know GraphQL is a solution but I wanted to know is there any other way around as I want this functionality just to replace DB calls where I just specify which object and its fields are required and I got those data. I don't want graphQL APIs.

For example: I have tables A, B and C, and if I have table B and C primary key as a foreign key in table A.

Let's say I am query table A data with Id 1 and then I can also include the data of table c which is linked with table A id 1 within the same query with include(x => x.tableC) . eg :-

db.Where<TableA>(x => x.id.equals(id)).include(x => x.tablec);

Now my requirement is like what data to include can be dynamic it can be only TableB(FieldA, FieldB) or it can be TableC(FieldA), TableB(FieldA, FieldB) or only TableC(FieldD) .

According to that, I want the result

And this thing what to include will be in a variable

As far as I understand from your question; and assuming that you store relation in variable so you can chain include :

Something like this:

//Lets say TableA has relation with tableB and tableC
List<string> tableARelations = new List<string>()
{
    "tableB",
    "tableC"
}


using (var dbContext = GetDbContext())
{
    var query = dbContext.TableA.AsQueryable();
    foreach (string include in tableARelations)
    {
        query = query.Include(include);
    }

    var result =  query.Where(x => x.Id.Equals(id)).FirstOrDefault();                    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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