I want to assign values to properties in my own class with automapper from the list I have. But it gives an error while giving value to reference type in clash.
json data; {recid: 182, MyBirim: {id: 37, text: "TUZLA"}, LokasyonAdi: "aaaaa", LokasyonAdresi: "bbbb"}
my database tables;
public MyInternetHatlari Convert(IDictionary<string, object> source,
MyInternetHatlari destination,
ResolutionContext context)
{
if (destination is null)
{
destination = new MyInternetHatlari()
{
İl = "ISTANBUL",
CreatedDateTime = DateTime.Now,
UserId = _httpContext.User.Identity.GetUserId()
};
}
Type type = destination.GetType();
IEnumerable<KeyValuePair<string, object>> keyValuePairs =
source.Where(x => x.Key != "recid" && !x.Key.EndsWith("Id"));
foreach (var (key, value) in keyValuePairs)
{
var propertyInfo = type.GetProperty(key);
if (propertyInfo is null) continue;
if (propertyInfo.PropertyType.Namespace is not null &&
propertyInfo.PropertyType.Namespace.StartsWith("System"))
{
Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
object safeValue = System.Convert.ChangeType(value, t);
propertyInfo.SetValue(destination, safeValue, null);
}
else
{
var job = JObject.Parse(value.ToString()).ToObject<SortedDictionary<string, object>>();
#region valuetype
var propinfo = type.GetProperty(key + "Id");
if (propinfo is not null)
{
Type t = Nullable.GetUnderlyingType(propinfo.PropertyType) ?? propinfo.PropertyType;
object safeValue = System.Convert.ChangeType(job["id"], t);
propinfo.SetValue(destination, safeValue, null);
}
#endregion
#region referancetype
Type proptype = propertyInfo.PropertyType;
if (proptype is null) continue;
DataTable dataTable = _db.DataTable("SELECT TOP (1) * from " + key + " where Id=" + job["id"]);
for (int i = 0; i < dataTable.Rows.Count; i++)
{
foreach (PropertyInfo pi in proptype.GetProperties().Where(p => p.PropertyType.IsSerializable))
{
object row = dataTable.Rows[i][pi.Name];
Type tt = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
object sv = System.Convert.ChangeType(row, tt);
//error TargetException: Object does not match target type.
pi.SetValue(proptype, sv, null);
}
}
propertyInfo.SetValue(destination, proptype, null);
#endregion
}
}
return destination;
}
"TargetException: Object does not match target type" on this line. Gives a fault. pi.SetValue(proptype, sv, null);
I get this error when I try to change the values of the relational table. I tried using Activator.CreateInstance to my relational class instead, it works but I can't "attach" with ef core.
Aucun commentaire:
Enregistrer un commentaire