使用LINQ和C#将行从一个表复制到另一个表 [英] Copying a row from one table to another using LINQ and C#
问题描述
我有两个表,它们是彼此的精确克隆(相同的列,只是将不同的列设置为主键).基本上,第二个表仅用于保留第一个表的历史记录.我需要做的是,当用户更新表1中的一条记录时,我需要将该记录的原始副本插入表2中.
I have two tables that are pretty much exact clones of one another (identical columns, just different columns set as primary keys). Basically the second table is just for keeping a history of the first table. What I need to do is, when a user updates a record in table 1 I need to insert the original copy of that record into table 2.
我正在使用LinqDataSource对象,并利用了LinqDataSource_Updating(object sender, LinqDataSourceUpdateEventArgs e)
事件,因此我可以访问e.OriginalObject
,这对于在表2中插入原始行是完美的.我的问题是我不想必须手动设置每个属性,因为其中大约有50个,因此我想使用Reflection,但不确定如何正确处理它.
I am using a LinqDataSource object and utilizing the LinqDataSource_Updating(object sender, LinqDataSourceUpdateEventArgs e)
event so I have access to e.OriginalObject
and that will be perfect for inserting the original row in table 2. My problem is that I don't want to have to set every property manually because there are about 50 of them, so I want to use Reflection but am not sure how to properly go about it.
考虑以下代码:
INSTRUMENT_DATA_SHEET _original = (INSTRUMENT_DATA_SHEET)e.OriginalObject;
INSTRUMENT_DATA_SHEET_HISTORY _history = new INSTRUMENT_DATA_SHEET_HISTORY();
如何将所有_original
的属性值复制到_history
的属性值?我尝试使用这个问题,但是它对我不起作用.它引发错误:
How can I go about copying all of the _original
's property values to _history
's? I have tried using the solution from this question, however it isn't working for me. It throws the error:
Property DATE has an incompatible type in E_and_I.INSTRUMENT_DATA_SHEET_HISTORY
我的猜测是,因为DATE
列是表2中主键的一部分,而不是表1中的主键.正如我所说,两个表之间的唯一区别是主键.这里供您参考:
My guess is that it's because the DATE
column is part of the primary key in table 2, but not table 1. As I said, the only difference between the two tables are the primary keys. Here they are for your reference:
推荐答案
好,我设法弄清楚了:)这是我所做的:
Ok I've managed to figure it out :) Here's what I did:
INSTRUMENT_DATA_SHEET _original = (INSTRUMENT_DATA_SHEET)e.OriginalObject;
INSTRUMENT_DATA_SHEET_HISTORY _history = new INSTRUMENT_DATA_SHEET_HISTORY();
foreach (PropertyInfo pi in _original.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
_history.GetType().GetProperty(pi.Name).SetValue(_history, pi.GetValue(_original, null), null);
}
不是很优雅,但是可以完成工作!
Not very elegant but it gets the job done!
这篇关于使用LINQ和C#将行从一个表复制到另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!