我有一个带有属性IList<string>
的域类,我希望将其映射到具有单个数据值的表(即它具有ID,域实体表的外键ID和varchar数据列)。
我一直收到错误:
关联引用未映射的类:System.String
如何将表格映射到字符串集合?
答案 0 :(得分:22)
我刚遇到类似的情况;我发现确实可以映射一组字符串。 请注意,您必须将这些字符串映射为值对象。
这就是我所拥有的:
public class Chapter
{
private ISet<string> _synonyms = new HashedSet<string>();
public ReadOnlyCollection<string> Synonyms
{
get { return new List<string>(_synonyms).AsReadOnly(); }
}
}
映射:
<class name="Chapter" table="Chapter">
<set name="Synonyms" table="ChapterSynonyms">
<key column="ChapterId" />
<element column="ChapterCode" type="string" />
</set>
</class>
答案 1 :(得分:8)
除非我弄错了,否则你可以这样做:
<bag name="Identities" access="property">
<key column="accountId"/>
<element column="identity" type="string"/>
</bag>
身份是IList<string>
答案 2 :(得分:1)
您可以使用IUserType执行此操作,如下所示:
public class DelimitedList : IUserType
{
private const string delimiter = "|";
public new bool Equals(object x, object y)
{
return object.Equals(x, y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var r = rs[names[0]];
return r == DBNull.Value
? new List<string>()
: ((string)r).SplitAndTrim(new [] { delimiter });
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
object paramVal = DBNull.Value;
if (value != null)
{
paramVal = ((IEnumerable<string>)value).Join(delimiter);
}
var parameter = (IDataParameter)cmd.Parameters[index];
parameter.Value = paramVal;
}
public object DeepCopy(object value)
{
return value;
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return cached;
}
public object Disassemble(object value)
{
return value;
}
public SqlType[] SqlTypes
{
get { return new SqlType[] { new StringSqlType() }; }
}
public Type ReturnedType
{
get { return typeof(IList<string>); }
}
public bool IsMutable
{
get { return false; }
}
}
然后定义IList&lt; string&gt; property as type =“MyApp.DelimitedList,MyApp”。
注意:SplitAndTrim是一个字符串扩展,包含我创建的各种覆盖。这是核心方法:
public static IList<string> SplitAndTrim(this string s, StringSplitOptions options, params string[] delimiters)
{
if (s == null)
{
return null;
}
var query = s.Split(delimiters, StringSplitOptions.None).Select(x => x.Trim());
if (options == StringSplitOptions.RemoveEmptyEntries)
{
query = query.Where(x => x.Trim() != string.Empty);
}
return query.ToList();
}