views:

71

answers:

2

The following method creates a linq-to-sql object at run time based on a class name.

I can also fill the properties of the item via reflection.

But how do I save this object via the linq-to-sql commands if I don't know at runtime which type it is?

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();
}
+1  A: 

I think you nead also one generic methot that will do the Linq inser like this

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

Then from your method you call this method:

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

}
Florim Maxhuni
+1  A: 

If you have a data-context, you can just use:

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

Fortunately, LINQ-to-SQL is very forgiving here...

One warning, though - it is safer to use assembly.GetType(string) (for an Assembly instance) that Type.GetType(string).

This and a lot of similar material is covered in a series of blog entries starting here covering writing an ADO.NET Data Services layer for LINQ-to-SQL (which has similar challenges to this).

Marc Gravell