samedi 24 octobre 2020

Insert multiple objects into the database dynamically using reflection and Ado.net

I am trying to solve it for a long time. Any assistance would be greatly appreciated. Basically, I need to insert multiple objects into the database dynamically. If any of my objects contain a generic list then I will have to work with that list too. I want to do that process recursively.

class Program
    {
        static void Main(string[] args)
        {
            var house1 = new House()
            {
                Id = 1,
                HouseName = "Hasan's villa",
                HouseAddress = "Riyadh",
                Rooms = new List<Room>() { new Room() { Id = 01, Rent = 1200,

                    Furnitures = new List<Furniture>() { new Furniture() { Id = 001, FurnitureName = "Table", Price = 45 },
                                                       { new Furniture() { Id = 002, FurnitureName = "Bookshelf", Price = 55 } } } },

                    new Room(){Id = 02, Rent = 1500, Furnitures = new List<Furniture> {new Furniture(){Id = 003 , FurnitureName = "Almari", Price = 75}} }

                }
            };

var connectionString = "Server=SQLEXPRESS//FERTILE-FIEL;Database=ASPNETB4;Trusted_Connection=True;";
            var dataOperation = new DataOperation<House>(connectionString);

            dataOperation.Insert(house1);
    }


class EntityMaker
    {
        public object genericProp { get; set; }
        public void InsertEntity(object entity)
        {
            Type type = entity.GetType();
            string name = type.Name;

    

    var propertyNames = new ArrayList();
    
            var propertyValue = new ArrayList();

//Need to make the sql dynamic. I have just hard coded it for now.

string sql = "INSERT INTO " + name + " (" + propertyNames[0]+',' + propertyNames[1]+','+ propertyNames [3]+") 
VALUES(" + propertyValues[0]+',' + propertyValues[1]+',' + propertyValues[2]+");";

        var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

        foreach (var prop in properties)
        {

            if (prop.PropertyType.IsGenericType)
            {
                genericProp = prop.PropertyType;
                Type genType = (Type)genericProp;
                var types = genType.GetGenericArguments()[0];

                var genName = types.Name;

                InsertEntity(genName);
            }
            else
            {
                var propName = prop.Name;
                var propValue = prop.GetValue(entity).ToString();

                if (propName != null)
                {
                    propertyNames.Add(propName).ToString();
                    propertyValue.Add(propValue).ToString();
                }
            }

        }

Thanks for considering my problem.





Aucun commentaire:

Enregistrer un commentaire