我想爲這個問題想出一個整潔的解決方案,使其可擴展。我有一個DataTable
dt,它的結構從數據庫中讀取。我希望能夠使用實體框架將這些數據正確地映射到正確的字段中,並允許代碼即使在添加或刪除列時也能正常工作。通過強類型字段循環實體框架c#
using (Entities db = new Entities())
{
foreach (DataRow dr in dt.Rows)
{
var result = db.myTable.SingleOrDefault(e => e.Email == dr["Email"].ToString());
foreach (SourceToDestinationMapping s in mapping)
{
// want to do something like this
result[s.DestinationColumn] = dt[s.DestinationColumn];
// instead of this
result.Name = dt["Name"].ToString();
result.Address = dt["Address"].ToString();
// all field mappings
}
}
}
這東西是可能的嗎?或者每次添加/刪除新列時是否需要更改代碼?如果這不是有效的話,那麼我可以在沒有Entity Framework的情況下切換到這樣的事情。
編輯:
例子是: 1,EmailAddress的,電子郵件,1
public partial class SourceToDestinationMapping
{
public int MappingId { get; set; }
public string SourceColumn { get; set; }
public string DestinationColumn { get; set; }
public bool Active { get; set; }
}
我們可以看到'SourceToDestinationMapping'類嗎? –
Automapper呢? https://www.geekytidbits.com/automapper-with-datatables/ –
@WilliamXifaras我不知道這對我有效,因爲如果我要添加/刪除列,那麼我需要編輯匹配數據表的類 –