Jeyanth
Jeyanth

Reputation: 78

c# set DataContext column values without strongly typing it

        //Instead of the this 
        var tableX = db.PRODUCT; //db is the DataContext
        //I can do the below (Thanks to http://stackoverflow.com/questions/1919632/get-table-data-from-table-name-in-linq-datacontext
        string tablename = "PRODUCT";
        var table = (ITable)db.GetType().GetProperty(tablename).GetValue(db, null);

        //But instead of this
        PRODUCT _Product = new PRODUCT();
        _Product.PRD_CODE = "code1";
        _Product.PRD_DESC = "description1";
        table.InsertOnSubmit(_Product);
        db.SubmitChanges();

        //How can I do something like this
        string tablename = "PRODUCT";
        var table = (ITable)db.GetType().GetProperty(tablename).GetValue(db, null);
        string lsColumnPrdCode = "PRD_CODE";
        string lsColumnPrdDesc = "PRD_DESC";
        table _tableInstance = new table();
        _tableInstance[lsColumnPrdCode] = "code1";
        _tableInstance[lsColumnPrdDesc] = "description1";
        _tableInstance.InsertOnSubmit(_tableInstance);
        db.SubmitChanges();

So it is possible to set datacontext column values without strongly typing it?

Upvotes: 0

Views: 829

Answers (1)

Jan
Jan

Reputation: 16032

Of cause you can use reflection to do that kind of stuff. Maybe something similar to this code:

Type productType = Type.GetType("PRODUCT");
var product = Activator.CreateInstance(productType);
productType.GetProperty("PRD_CODE").SetValue(product, "code1");
productType.GetProperty("PRD_DESC").SetValue(product, "description1");

Type tableType = table.GetType();
tableType.GetMethod("InsertOnSubmit").Invoke(table, new object[] {product});

But why do you want to do that?

Upvotes: 1

Related Questions