Home > front end >  C# - Check if the property on a model is a Key
C# - Check if the property on a model is a Key

Time:12-22

I'm currently creating my own ORM for my current employer, because they have restriction when it comes to packages on nuget, installing them on my projects requires approval, and it take weeks or month before they approve it (from the next level to the highest level), that's why I'm creating my own ORM, but not all tables on our database have an Id or primary key with different name (legacy applications), that's why I'm planning to make it flexible.

Let's say I have a model with a primary key

public class Sample
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    public string LastName { get; set; }
    [Required]
    public int Age { get; set; }

    [StringLength(255)]
    public string Hobby { get; set; }
}

then I create an insert method which adds the data to the database table, now this works if the primary key's name is only "Id", but on the legacy databases that has a different name, like below

[Key]
public int EntryNo { get; set; }

or this

[Key]
public string TransNo { get; set; }

I want the code on my insert to determine if the property is a primary key or not, what my code is doing now is this.

public T InsertData<T>(T model)
{
    using (SqlConnection SqlConn = new SqlConnection(_connectionString))
    {
        T GetResult;
        Type t = typeof(T);
        Type ObjType = model.GetType();
                
        string SqlParameter = "";
        string SqlValue = "";
        PropertyInfo[] prop = ObjType.GetProperties();
        for(int i = 0; i < prop.Length; i  )
        {
            if (prop[i].Name != "Id") //I want this to be replace to check if the property is a primary key
            {
                SqlParameter = (SqlParameter == "") ? $"[{prop[i].Name}]" : $"{SqlParameter},[{prop[i].Name}]";
                SqlValue = (SqlValue == "") ? $"'{prop[i].GetValue(model).ToString()}'" : $"{SqlValue},'{prop[i].GetValue(model).ToString()}'";
            }
        }
        string SqlString = $"insert into [{ObjType.Name}]({SqlParameter})values({SqlValue})";

        SqlCommand SqlCmd = new SqlCommand(SqlString, SqlConn);
        SqlConn.Open();
        SqlCmd.ExecuteNonQuery();
        SqlConn.Close();

        //Get Inserted data
        GetResult = GetInsertData(model);
        return GetResult;
    }
}

now I want to change the if statement to check if the property is a primary key or not, so it does not stick to "Id" only, and it can also work for our legacy applications.

Currently I'm searching on the internet, but I cannot see anything for this.

CodePudding user response:

Have a look at the below problem's solution, the premise of your issue is the same.

Similar problem

CodePudding user response:

You could look for the DataAnnotations KeyAttribute.

    public T InsertData<T>(T model)
    {
        using (SqlConnection SqlConn = new SqlConnection(_connectionString))
        {
            T GetResult;
            Type t = typeof(T);
            Type ObjType = model.GetType();

            string SqlParameter = "";
            string SqlValue = "";
            PropertyInfo[] props = ObjType.GetProperties();
            PropertyInfo prop = null;
            for (int i = 0; i < props.Length; i  )
            {
                if (props[i].Name == "Id") //I want this to be replace to check if the property is a primary key
                {
                    prop = props[i];
                    break;
                }

                object[] attrs = props[i].GetCustomAttributes(typeof(KeyAttribute), false);
                if (attrs.Length > 0)
                {
                    prop = props[i];
                    break;
                }
            }

            if (prop == null)
            {
                throw new Exception("pk not found");
            }
            SqlParameter = (SqlParameter == "") ? $"[{prop.Name}]" : $"{SqlParameter},[{prop.Name}]";
            SqlValue = (SqlValue == "") ? $"'{prop.GetValue(model).ToString()}'" : $"{SqlValue},'{prop.GetValue(model).ToString()}'";


            string SqlString = $"insert into [{ObjType.Name}]({SqlParameter})values({SqlValue})";

            SqlCommand SqlCmd = new SqlCommand(SqlString, SqlConn);
            SqlConn.Open();
            SqlCmd.ExecuteNonQuery();
            SqlConn.Close();

            //Get Inserted data
            GetResult = GetInsertData(model);
            return GetResult;
        }
    }
  • Related