I am using SQL Server 2008 R2 and asp.net, C#.

This code is a class that my entities inherits from it.

public class MySqlDataBase
{
    public void Insert()
    {
        try
        {
            int Inserted_Id = 0;
            Connect();
            Connection.Open();

            sqlCommand.CommandText = this.GetType().Name + "_INSERT";

            foreach (PropertyInfo item in this.GetType().GetProperties())
            {
                if (item.Name == "Id" || item.Name.Contains("_"))
                {
                    continue;
                }
                sqlCommand.Parameters.Add(new SqlParameter(item.Name, item.GetValue(this, null) != null ? item.GetValue(this, null) : DBNull.Value));

            }

            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Connection = Connection;
            Inserted_Id = Convert.ToInt32(sqlCommand.ExecuteScalar());

            Affected_Rows = 1;

            if (Inserted_Id == -1)
            {
                Inserted_Id = -1;
            }

            foreach (PropertyInfo item in this.GetType().GetProperties())
            {
                if (item.Name == "Id")
                {
                    item.SetValue(this, Inserted_Id, null);
                    break;
                }
            }
        }
        catch (ApplicationException ee)
        {
            throw ee;
        }
        catch (Exception ee)
        {
            throw ee;
        }
        finally
        {
            Finish();
        }
    }
}

My procedure is :

CREATE PROCEDURE SiteUserBuyInfo_INSERT(
    @Email nvarchar(100) , 
    @Family nvarchar(11))
AS 
BEGIN 
    INSERT INTO SiteUserBuyInfo (Email, Family) 
    OUTPUT INSERTED.Id 
    VALUES (@Email, @Family)  
END

My entity is:

public class User : MySqlDataBase
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Family { get; set; }
}

When I use User.Insert() sometimes (not always) set wrong Id from OUTPUT clause to the Id property of Object.

Why?

Related posts

Recent Viewed