使用 LINQ 将行插入任何 table

Insert row to any table with LINQ

我想用 LINQ 开发动态插入方法。

假设我有两个 table,例如:

Product
{
   id int,
   name varchar(20),
   price int
}

Factory
{
   id int,
   name varchar(50),
   address varchar(240)
}

但是,考虑到我不知道 table,只知道他们的名字。

这就是我如何获取 table 的列名称,我知道它的名称是:

var db = new DataContext();
var columnNames = db.Mapping.MappingSource
                      .GetModel(typeof(DataContext))
                      .GetMetaType(typeof(table_name))
                      .DataMembers;

但我不知道如何获取 table 的列名称,我 不知道 的名称。到目前为止我尝试了什么:

context.Mapping.GetTables().FirstOrDefault(
                x=> x.TableName == table_name ).Model.ContextType.Attributes;

table_name 是动态变化的,比如:Product, Factory 等。但我认为这种方式是死胡同。

所以,最后我不知道如何获取随机 table 的列名,更不用说向随机 table.

插入一行了

我可以使用 SqlCommands 以经典方式做到这一点,但我想知道如何使用 LINQ 做到这一点。

正如 Mant101 在他的评论中所说:

I don't think Linq is going to help here. You could write some code in ADO.NET to get the columns definitions from the database, then use some reflection to build an insert/update statement based on the properties of the object that match the columns. I would ask why you need to do this, are you working with some database that is in an unknown state when the app run?

当 StriplingWarrior 对他表示支持时:

Mant101 is right: The whole purpose of an object-relational mapper is to make it easier to work with persisted data by converting it into objects that you can use in the programming language. Since you're not going to program against those objects in this case, you don't get any value from LINQ-to-SQL. You're better off bypassing the ORM and using straight SQL/ADO.NET.

使用 LINQ 的泛型方法插入任何 table 似乎是不可能的。 但是,您可以使用 SQL.