我正在使用以下代碼:
public static List<T> ConvertToList1<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
T objT1 = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
{
PropertyInfo? pI = objT.GetType().GetProperty(pro.Name);
pro.SetValue(objT, row[pro.Name] == DBNull.Value ? null : Convert.ChangeType(row[pro.Name], pI.PropertyType));
}
}
return objT1;
}).ToList();
}
但是對于具有空值的十進制欄位,我收到錯誤訊息。
從 'System.Decimal' 到 'System.Nullable'1 [[System.Decimal, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral 的無效轉換
public class SampleModel
{
public Guid Id { get; set; }
public Guid ProjectId { get; set; }
public string? Code { get; set; } = null!;
public string? Description { get; set; }
public decimal? Quantity1 { get; set; }
public decimal? Quantity2 { get; set; }
}
誰能建議如何解決這個問題?
uj5u.com熱心網友回復:
嗯,再讀一遍......你的意思是不能將行中的非空十進制值分配給可為空的小數?還是您的意思是不能分配給可空小數的 dbnull ?
您可以使用DataRow.IsNull來檢查該值是否為 dbnull。在這種情況下,您只需跳過它,因為可空物件已經具有默認空值。
// <CODE SNIP />
if (columnNames.Contains(pro.Name))
{
// if the value was null, just skip it.
if(!row.IsNull(pro.Name))
{
PropertyInfo? pI = objT.GetType().GetProperty(pro.Name);
pro.SetValue(objT, Convert.ChangeType(row[pro.Name], pI.PropertyType));
}
}
uj5u.com熱心網友回復:
我有戲。@Ryan Wilson 的鏈接非常有用。
簡而言之,當您有一個可為空的型別時,您希望轉換為基礎型別。考慮:
decimal? target;
decimal source = 42;
target = source;
這是完全合理的代碼。我們可以給decimal變數decimal?賦值。
UsingNullable.GetUnderlyingType(myType)回傳一個型別,如果myType不可為空,則回傳 null。擴展上面的代碼片段:
var underlying1 = Nullable.GetUnderlyingType(target.GetType());
var underlying2 = Nullable.GetUnderlyingType(source.GetType());
在這里,underlying2是null,underlying1是decimal。
然后,為了將其付諸實踐,我們將轉換方法的最里面部分稍微更改為:
PropertyInfo pI = objT1.GetType().GetProperty(pro.Name);
var targetType = Nullable.GetUnderlyingType(pI.PropertyType) ?? pI.PropertyType;
pro.SetValue(objT1, row[pro.Name] == DBNull.Value
? null
: Convert.ChangeType(row[pro.Name], targetType));
uj5u.com熱心網友回復:
嘗試以下:
public static List<SampleModel> ConvertToList1<T>(DataTable dt)
{
List<SampleModel> results = dt.AsEnumerable().Select(x => new SampleModel()
{
Id = x.Field<Guid>("Id"),
ProjectId = x.Field<Guid>("ProjectId"),
Code = x.Field<string>("Code"),
Description = x.Field<string>("Description"),
Quantity1 = x.Field<decimal>("Quantity1"),
Quantity2 = x.Field<decimal>("Quantity1")
}).ToList();
return results;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/515635.html
標籤:C#林克数据表
下一篇:在界面中選擇以獲得更好的性能
