【问题标题】:C# GUID and SQL Server Uniqueidentifier conversionC# GUID 和 SQL Server 唯一标识符转换
【发布时间】:2018-01-20 09:18:21
【问题描述】:

我正在尝试绘制一个谷歌图表,我肯定是通过存储过程从我的 SQL Server 数据库中获取数据,但是我在使用 UserID 参数时遇到了困难,因为它是一个唯一标识符。如果我使用activityID 参数(int),一切正常。您能否指导我如何将我的 userid 唯一标识符转换为 int?

存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[rpGetUserActivities]
    (--@UserID uniqueidentifier, <----- I would like to use this
     @ActivityID INT)
AS   
BEGIN  
    SELECT  
        [UserID],
        [ActivityID],
        [Title],
        [DateCreated]
    FROM 
        [DB].[dbo].[DB_Activity]
    WHERE 
        [DateCreated] IS NOT NULL  
        AND [ActivityID] = @ActivityID
        -- [UserID] = @UserID <----- I would like to use this
END 

类:

namespace ChartLibrary
{
    public class rpusersAction
    {
        /// <summary>
        /// Specify the Database variable
        /// </summary>
        Database objDB;

        /// <summary>
        /// Specify the static variable
        /// </summary>
        string ConnectionString;

        public List<T> ConvertTo<T>(DataTable datatable) where T : new()
        {
            List<T> Temp = new List<T>();

            try
            {
                List<string> columnsNames = new List<string>();

                foreach (DataColumn DataColumn in datatable.Columns)
                    columnsNames.Add(DataColumn.ColumnName);

                Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
                return Temp;
            }
            catch
            {
                return Temp;
            }
        }

        public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
        {
            T obj = new T();

            try
            {
                string columnname = "";
                string value = "";
                PropertyInfo[] Properties;
                Properties = typeof(T).GetProperties();

                foreach (PropertyInfo objProperty in Properties)
                {
                    columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());

                    if (!string.IsNullOrEmpty(columnname))
                    {
                        value = row[columnname].ToString();

                        if (!string.IsNullOrEmpty(value))
                        {
                            if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                            {
                                value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                            }
                            else
                            {
                                value = row[columnname].ToString();
                                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
                            }
                        }
                    }
                }

                return obj;
            }
            catch (Exception ex)
            {
                return obj;
            }
        }

        /// <summary>
        /// This constructor is used to get the connection string from the config file
        /// </summary>
        public rpusersAction()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings["connName"].ToString();
        }

        /// <summary>
        /// This method is used to get all users
        /// </summary>
        /// <returns></returns>
        public List<rpusers> GetrpusersDetails()
        {
            List<rpusers> objrpusers = null;
            objDB = new SqlDatabase(ConnectionString);

            using (DbCommand objcmd = objDB.GetStoredProcCommand("rpGetUsers"))
            {
                try
                {
                    using (DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0])
                    {
                        objrpusers = ConvertTo<rpusers>(dataTable);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                    return null;
                }
            }

            return objrpusers;
        }
        /// <summary>
        /// This method is used to get player records on the basis of userid
        /// </summary>

        /// <returns></returns>  I'm testing using an INT
        public List<rpusersRecord> rpGetUserActivities(Int16? ActivityID)
        {
            List<rpusersRecord> objrpusersRecords = null;
            objDB = new SqlDatabase(ConnectionString);

            using (DbCommand objcmd = objDB.GetStoredProcCommand("rpGetUserActivities"))
            {
                objDB.AddInParameter(objcmd, "@ActivityID", DbType.Int64, ActivityID);

                try
                {
                    using (DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0])
                    {
                        objrpusersRecords = ConvertTo<rpusersRecord>(dataTable);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                    return null;
                }
            }

            return objrpusersRecords;
        }
    }
}

再次感谢您!

【问题讨论】:

    标签: c# asp.net sql-server asp.net-mvc


    【解决方案1】:

    您可以将唯一标识符转换为 int。只需添加 UserId 参数作为唯一标识符即可。

    var userId = new Guid("96d5b379-7e1d-4dac-a6ba-1e50db561b04");
    objDB.AddInParameter(objcmd, "@UserID", SqlDbType.UniqueIdentifier, userId);
    

    【讨论】:

    • 谢谢,var userId = new Guid("96d5b379-7e1d-4dac-a6ba-1e50db561b04");
    • 不,我只是提供了一个样本。您应该将参数作为 Guid 而不是字符串传递,因此将字符串解析为 Guid。
    【解决方案2】:

    如果你想在每次调用时传递新的 GUID,那么你可以使用 like

    var userID = Guid.NewGuid();   // Always returns a new GUID
    
    objDB.AddInParameter(objcmd, "@UserID", SqlDbType.UniqueIdentifier, userId);
    

    注意:GUID 在空间和时间上总是唯一的

    【讨论】:

      猜你喜欢
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      相关资源
      最近更新 更多