//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();
那么可以设置datacontext列值而无需强烈输入吗?
答案 0 :(得分:1)
因为你可以使用反射来做那种事情。也许类似于这段代码:
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});
但你为什么要那样做?