jeudi 11 juillet 2019

Reflect Table/Column names based on data annotation

I want to derive table and column names at runtime based on data annotations. In my code sample I am hard coding values for now but I want to do it the right way. Searched around but I cannot find a solution.

[Table("T_MY_TBL")]
public class MyTable
{
    [Column("ID")]
    public int Id { get; set; }
    [Column("FNAME")]
    public string FirstName { get; set; }
}

public class MyLogic
{
    public void Save(List<MyTable> recs)
    {
        using (SqlConnection conn = new SqlConnection(connectionsTring))
        {
            conn.Open();
            using (SqlBulkCopy bc = new SqlBulkCopy(conn))
            {
                // want to reflect data-annotations instead of hard coding values
                using (var reader = FastMember.ObjectReader.Create(recs, "ID", "FNAME"))
                {
                    // want to reflect data-annotations instead of hard coding values
                    bc.DestinationTableName = "T_MY_TBL";
                    bc.WriteToServer(reader);
                }

            }
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire