2009-12-04 70 views
2

以下方法創建 linq-to-sql對象運行時間基於類名稱如何通過反射動態創建並保存LINQ-to-SQL對象?

我也可以通過反射填充物品的屬性

但是我如何通過linq-to-sql命令保存這個對象,如果我在運行時不知道它是哪種類型的話?

public void CreateItem(string className) 
{ 
    //create instance of item 
    string classNamespaceAndName = "TestApp.Models." + className; 
    Type itemType = Type.GetType(classNamespaceAndName); 
    item = (object)Activator.CreateInstance(itemType, new Object[] { }); 

    //fill properties through reflection 

    //save item to the database 
    db.?????.InsertOnSubmit(item as itemType); //error 
    db.SubmitChanges(); 
} 

回答

2

我想你NEAD也是一個通用的methot,將做的LINQ inser這樣

public void Insert<T>(T obj) where T : class 
{ 
    using (var db = GetData()) 
    { 
     db.GetTable<T>().InsertOnSubmit(obj); 
     db.SubmitChanges(); 
    } 
} 

然後從你的方法調用此方法:

public void CreateItem(string className) 
{  
    string classNamespaceAndName = "TestApp.Models." + className;  
    Type itemType = Type.GetType(classNamespaceAndName);  
    item = (object)Activator.CreateInstance(itemType, new Object[] { });  
    this.insert(item); 

} 
3

如果你有一個數據上下文,你可以使用:

ctx.GetTable(itemType).InsertOnSubmit(item); 

幸運的是,LINQ到SQL是非常寬容這裏...

一個警告,雖然 - 它是安全使用assembly.GetType(string)(對於Assembly)瞭解到Type.GetType(string)

這和許多類似的材料被覆蓋在一系列博客文章starting here中,涵蓋了爲LINQ-to-SQL(與此類似的挑戰)編寫ADO.NET數據服務層。