2011-09-19 3 views
0
 //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 열 값을 설정할 수 있습니까?강하게 입력하지 않고 DataContext 열 값을 설정할 수 있습니다.

+0

확실히 가능합니다. 결국 C#은 재귀 적 언어입니다. 우리는 프로젝트에서 그렇게했습니다. 그러나 그것은 너무 많은 코드입니다. 나는 지쳤다. – Nawaz

답변

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}); 

하지만 왜 그렇게하고 싶습니까?

+0

감사합니다 1 월. 참조 데이터가있는 50 개 이상의 테이블이 있고이 데이터는 XML에서 가져온 값 (웹 서비스를 통해 다운로드 됨)에서 새로 고쳐집니다. 테이블과 컬럼 이름은 XML의 요소 이름이며 테이블 당 하나의 루틴을 입력하는 대신 일반화하기를 원했기 때문에 하나의 루틴이 XML 요소 이름을 기반으로 모든 테이블을 처리합니다. DataContext 및 Java (Android 기반)없이 C# (DataTable 및 TabelDirect 명령 사용)에서 수행했으며 WindowsPhone 7에서도 동일한 작업을 수행하려고했습니다. XmlReader를 사용하여 읽고 있습니다. – Jeyanth

+0

유형 productType = db.GetType(). GetProperty ("PRODUCT"). GetValue (db, null) .GetType(); var product = Activator.CreateInstance (productType); // 매개 변수없는 생성자가 없습니다. 오류가 발생했습니다 (methodmissingexception) // 그렇게 시도했습니다 ... var ctor = productType.GetConstructor (new Type [] {}); var obj = ctor.Invoke (새 객체 [] {}); // ctor 값이 null이므로 여전히 오류가 발생합니다. 어떤 제안? – Jeyanth

+0

PRODUCT 클래스에 매개 변수없는 생성자가 없으면 CreateInstance 호출에서 매개 변수 값을 지정해야합니다. – Jan

관련 문제