[英]How to copy table records from one table to another in different databases
[英]Unable to copy records from one table to another in Entity Framework MVC
我一直在嘗試將記錄從一個表復制到Entity Framework MVC中的另一個表。 這是我的代碼。
var records = _db.Attendance.Get(e => attIdsToDelete.Contains(e.Id));
_db.AttendanceHistory.Insert(records);
現在,我在“無法從'system.collections.generic.ienumerable'轉換為'attendancehistory'的記錄上收到錯誤信息
數據庫中的列數和類型均相同。
請改變這個
_db.AttendanceHistory.Insert(records);
對此:
_db.AttendanceHistory.AddRange(records);
如果Attendance和AttendanceHistory是同一類型,則此方法應該起作用。 如果仍然有問題,請嘗試先投射並更改為列表:
var records = _db.Attendance.Get(e => attIdsToDelete.Contains(e.Id)).ToList<AttendanceHistory>();
您可以創建如下所示的方法,並將所有屬性(值)從源類復制到目標類(如果兩個類具有相同的屬性(名稱和數據類型)
public class Utility
{
/// <summary>
/// Copy one class all properties to another class - if both the class having all the same properties
/// </summary>
/// <param name="FromClass">Class A - from where properties need to be copied</param>
/// <param name="ToClass">Class B - to whom properties need to be pasted</param>
public static void CopyAllPropertiesFromOneClassToAnotherClass(object FromClass, object ToClass)
{
foreach (PropertyInfo propA in FromClass.GetType().GetProperties())
{
PropertyInfo propB = ToClass.GetType().GetProperty(propA.Name);
propB.SetValue(ToClass, propA.GetValue(FromClass, null), null);
}
}
}
然后在代碼中,您可以調用該方法以復制數據,如下所示
Utility.CopyAllPropertiesFromOneClassToAnotherClass(fromClassObject, toClassObject);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.