我是Dapper
和Dapper.Contrib
的新手。有一个这样的类,数据库中有一个同名的表:
public class Ware
{
public int ID { get; set; }
public string Name { get; set; }
public short UnitID { get; set; }
public short TypeID { get; set; }
public int CableCodeID { get; set; }
public string Tag1 { get; set; }
public string Tag2 { get; set; }
public bool Discontinued { get; set; }
public decimal Stock { get; set; } //this is not in database. this is helper
public string UnitCaption { get; set; } //this is not in database. this is helper
public string TypeCaption { get; set; } //this is not in database. this is helper
public string FullCaption //this is not in database. this is helper
{
get
{
return $"{ID} {Name}";
}
}
}
我需要将此类的完整列表更新为数据库。我用:
conection.Update(myList); // myList is List<Ware>
但是当它运行时出现错误:
System.Data.SqlClient.SqlException: 'Invalid column name 'Stock'.'
System.Data.SqlClient.SqlException: 'Invalid column name 'UnitCaption'.'
System.Data.SqlClient.SqlException: 'Invalid column name 'TypeCaption'.'
System.Data.SqlClient.SqlException: 'Invalid column name 'FullCaption'.'
如何解决这个问题?
答案 0 :(得分:1)
从Dapper.Contrib
源代码复制代码:
<强>已计算强>
[AttributeUsage(AttributeTargets.Property)]
public class ComputedAttribute : Attribute { }
在代码中使用Computed:
private static List<PropertyInfo> ComputedPropertiesCache(Type type)
{
IEnumerable<PropertyInfo> pi;
if (ComputedProperties.TryGetValue(type.TypeHandle, out pi))
{
return pi.ToList();
}
var computedProperties = TypePropertiesCache(type).Where(p => p.GetCustomAttributes(true).Any(a => a is ComputedAttribute)).ToList();
ComputedProperties[type.TypeHandle] = computedProperties;
return computedProperties;
}
现在Insert<T>
和Update<T>
包含以下代码:
var computedProperties = ComputedPropertiesCache(type);
var allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties.Union(computedProperties)).ToList();
现在allPropertiesExceptKeyAndComputed
会在代码中进一步处理。
<强> WriteAttribute 强>
public class WriteAttribute : Attribute
{
public WriteAttribute(bool write)
{
Write = write;
}
public bool Write { get; }
}
在代码中使用IsWriteable:
private static List<PropertyInfo> TypePropertiesCache(Type type)
{
IEnumerable<PropertyInfo> pis;
if (TypeProperties.TryGetValue(type.TypeHandle, out pis))
{
return pis.ToList();
}
var properties = type.GetProperties().Where(IsWriteable).ToArray();
TypeProperties[type.TypeHandle] = properties;
return properties.ToList();
}
private static bool IsWriteable(PropertyInfo pi)
{
var attributes = pi.GetCustomAttributes(typeof(WriteAttribute), false).AsList();
if (attributes.Count != 1) return true;
var writeAttribute = (WriteAttribute)attributes[0];
return writeAttribute.Write;
}
现在注意上面粘贴的功能ComputedPropertiesCache
Computed 它调用方法TypePropertiesCache
,因此会发生什么,它会排除这两个属性({{1}但是Write("false")
} Computed
属性用于从Caching中排除Type属性,该属性是使用Write
创建的,ConcurrentDictionary
,非常适合您的使用案件。希望它有所帮助。