简体   繁体   中英

Convert Class Name Variable to Class Type c#

I am implementing web api methods to return some data. It works fine until we want to introduce new parameter to determine whether we should return Extra Detail of the Offering or just the normal detail.

My original code is like the following:

 using (IDbConnection conn = _context.Database.GetDbConnection())
                {


                var parameters = new
                {
                    CourseName = model.query,
                    CourseType = model.CourseType,
                    other parameters....
                };

                var obj = await conn.QueryAsync<Offering> ("SearchOfferings", parameters, commandType: CommandType.StoredProcedure);

                if (obj == null)
                    return NotFound("Record not found");

                return new ObjectResult(obj);
            }

I am using DAPPER to execute the stored procedures.

Now, we have added Extra parameter from querystring and added the logic to the existing code. If Extra = True, we want to return FullDetail with Different Object Type. otherwise, return only the Brief data.

I would like to know how can I pass the objectToReturn value in QueryAsync (dynamic param) method?

string objectToReturn = string.Empty;
if (extra)
    objectToReturn = "Offering";
else
    objectToReturn= "BriefOffering";    

var obj = await conn.QueryAsync<**objectToReturn**> ("SearchOfferings", parameters, commandType: CommandType.StoredProcedure);

When the client can change the query parameters in order to get detailed offerings then it might as well just access a different resource exposing your detailed offerings instead.

Suppose your current REST API resource for the offerings is:

http:\server.com\offerings\{id}

Why not have a second one like:

http:\server.com\detailedOfferings\{id}`

This makes your REST interface easier to use and understand while also simplifying the implementation.

If you really want to stick to the query parameter switch then you can just make a conditional call to one of the two generically typed methods:

if (extra)
    return await conn.QueryAsync<Offering>(
        "SearchOfferings", parameters, commandType: CommandType.StoredProcedure);
else
    return await conn.QueryAsync<BriefOffering>(
        "SearchOfferings", parameters, commandType: CommandType.StoredProcedure);

Dapper does have alternate Query / QueryAsync method signatures that might help you - there is one that will return a set of objects where each object is a type that is specified via a method argument rather than a generic type parameter.

This would allow you to do something like this:

var typeToReturn = Type.GetType("MyProject.Entities.Offering");
var obj = await conn.QueryAsync(
    type: typeToReturn,
    sql: "SearchOfferings",
    param: parameters,
    commandType: CommandType.StoredProcedure
);

The type name must be the full name of the desired type, so if the QueryString value was going to specify only "Offering" then you would have to know what namespace that that entity would be in and change the code to something like

var nameOfType = "Offering";

const string entityNamespace = "MyProject.Entities";
var typeToReturn = Type.GetType(entityNamespace + "." + nameOfType);
var obj = await conn.QueryAsync(
    type: typeToReturn,
    sql: "SearchOfferings",
    param: parameters,
    commandType: CommandType.StoredProcedure
);

Of course, having the return type be IEnumerable<object> means that you can't easily do much directly with the returned data but that was always going to be the case if you wanted to write some code to return dynamically-typed code; you wouldn't know at compile time what types were going to come back. If you're just going to serialise it to JSON, for example, then that's no big deal.

I just wanted to add this answer since it directly addresses what you asked - but I do also agree with Sam C's comment that you might be better using the method signature that returns IEnumerable<dynamic> if you honestly don't care about what types are returned.

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