问题描述:

I am using code like this in my C# controllers. db is my EF database context.

var sql = @"dbo.sp_add_test @CreatedBy,

@CreatedDate,

@TestId,

@TestStatusId";

// Can the following 7 lines be combined?

List<SqlParameter> parameterList = new List<SqlParameter>();

parameterList.Add(new SqlParameter("@CreatedBy", Int32.Parse(User.Identity.GetUserId()) ));

parameterList.Add(new SqlParameter("@CreatedDate", DateTime.UtcNow));

parameterList.Add(new SqlParameter("@TestId", testId));

parameterList.Add(new SqlParameter("@TestStatusId", 3));

SqlParameter[] parameters = parameterList.ToArray();

var test = await db.Database.SqlQuery<Test>(sql, parameters).FirstOrDefaultAsync();

It seems that there may be some redundancy in that I first create a list, then do individual adds to it and then finally convert to an array.

Is there a way all of this could be combined into one statement?

Please when you answer this question can you do so in the form of an answer and not in the comments so that everyone can be helped. Thanks in advance.

网友答案:

You can directly initialize the array as below:

SqlParameter[] parameterList = new SqlParameter[]
{
    new SqlParameter("@CreatedBy", Int32.Parse(User.Identity.GetUserId())),
    new SqlParameter("@CreatedDate", DateTime.UtcNow),
    new SqlParameter("@TestId", testId),
    new SqlParameter("@TestStatusId", 3)
};

But like the others said, if you are using EF, you can map the SP to the EF context by importing the SP to the EF context.

相关阅读:
Top