简体   繁体   中英

Create a Generic Object in C#

How do I create a class that should look like this:

public class DynamicObject<T> 
{
   public T PassedObject { get;set; }
   string RepositoryMessage { get; set; } = string.Empty;
}

In my Repository I can return an object if it gets a result from the db. This is supposed to be placed in the T. But if I don't get any result, then the T should be null and the RepositoryMessage should have a message. Please see my sample code for the repository

public async Task<DynamicObject<UserModel>> GetUser(SomeObject object) 
{
   UserModel um = new UserModel();
   DynamicOBject do = new DynamicObject<UserModel>();
   DB CALLS HERE....
   var responseCode = cmd.Parameters["@ResponseCode"].Value
   var responseMessage = cmd.Parameters["@ResponseCode"].Value
   if (response == 0) 
   {
     ....
     um.FName = reader.GetString(0);
     um.LName = reader.GetString(1);
     // The DynamicObject should now look like this:
     PassedValue = UseModel and the RepositoryMessage = string.Empty
     ....
   } else {
     do.PassedObject = null;
     do.RepositoryMessage = responseMessage;
     // The DynamicObject should now look like this:
     PassedValue = null and the RepositoryMessage = WHATEVER the responseMessage is from the SP.
   }
   return do;
}

I don't know if there is an existing technique for this. But this is the only way I think I can get the message of the database and pass it along to the controller and pass it to the client through the error like this => return BadRequest(respository.RepositoryMessage);

Thank you.

EDIT:

I don't know if this is correct or a standard practice, but this is what I came up with:

public class GenericResponse<T>
{
    public string RepositoryMessage { get; set; } = string.Empty;
    public T? ModelToReturn { get; set; }
}

public async Task<GenericResponse<ApplicationUser>> AuthenticateUser(UserLoginModel model)
{
    ApplicationUser user = new ApplicationUser();
    GenericResponse<ApplicationUser> response = new GenericResponse<ApplicationUser>();
    try
    {
        using (_connection = new SqlConnection(_helper.GetConnectionString()))
        {
            using(var cmd = _connection.CreateCommand())
            {
                cmd.CommandText = "UserLogin";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = _helper.GetCommandTimeout();

                var pUserName = new SqlParameter
                {
                    ParameterName = "@UserName",
                    DbType = DbType.String,
                    Size = 20,
                    Direction = ParameterDirection.Input,
                    Value = model.UserName
                };
                cmd.Parameters.Add(pUserName);

                var pPassword = new SqlParameter
                {
                    ParameterName = "@Password",
                    DbType = DbType.String,
                    Size = 35,
                    Direction = ParameterDirection.Input,
                    Value = model.Password
                };
                cmd.Parameters.Add(pPassword);

                var pResponseCode = new SqlParameter
                {
                    ParameterName = "@ResponseCode",
                    DbType = DbType.Int16,
                    Direction = ParameterDirection.Output,
                };
                cmd.Parameters.Add(pResponseCode);

                var pResponseMessage = new SqlParameter
                {
                    ParameterName = "@ResponseMessage",
                    DbType = DbType.String,
                    Size = 75,
                    Direction = ParameterDirection.Output,
                };
                cmd.Parameters.Add(pResponseMessage);

                await _connection.OpenAsync();
                cmd.ExecuteNonQuery();

                var responseCode = int.Parse(cmd.Parameters["@ResponseCode"].Value.ToString());
                var responseMessage = cmd.Parameters["@ResponseMessage"].Value.ToString();

                if (responseCode == 0)
                {
                    using (var reader = cmd.ExecuteReader())
                    {
                        while(reader.Read())
                        {
                            user.FirstName = reader.GetString(0);
                            user.LastName = reader.GetString(1);
                            user.UserRole = reader.GetString(2);
                        }
                    }
                    response.ModelToReturn = user;
                    response.RepositoryMessage = string.Empty;
                } else
                {
                    response.ModelToReturn = user;
                    response.RepositoryMessage = responseMessage;
                }
            }
        }
    }
    catch (Exception ex)
    {
        _helper.LogErrorMessage(ex.StackTrace, Models.LoggerModel.LoggingType.Error);
        response.ModelToReturn = user;
        response.RepositoryMessage = "An error has occured in loggin in";
    }
    return response;
}

I'm not sure if there is a general rule, but I use in Cotroller :

return StatusCode(result.StatusCode, result.Data);

for a good query, status code 200 returns only data.

Based on validate or using try catch for query, I return the best matching statuses, the Data now as error message, not just BadRequest

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