有人知道如何在NHibernate中使用Fluent自动映射自动映射动态组件吗?
我知道我们可以将普通类映射为组件,但不知道如何使用fluent自动映射将字典映射为动态组件。
谢谢
发布于 2011-07-06 18:45:27
我们已经成功地使用了以下方法(使用FluentNH 1.2.0.712):
public class SomeClass
{
public int Id { get; set; }
public IDictionary Properties { get; set; }
}
public class SomeClassMapping : ClassMap<SomeClass>
{
public SomeClassMapping()
{
Id(x => x.Id);
// Maps the MyEnum members to separate int columns.
DynamicComponent(x => x.Properties,
c =>
{
foreach (var name in Enum.GetNames(typeof(MyEnum)))
c.Map<int>(name);
});
}
}在这里,我们将一些枚举的所有成员映射到单独的列,其中所有列的类型都是int。现在,我正在处理一个场景,我们对动态列使用不同的类型,如下所示:
// ExtendedProperties contains custom objects with Name and Type members
foreach (var property in ExtendedProperties)
{
var prop = property;
part.Map(prop.Name).CustomType(prop.Type);
}这也是非常有效的。
我仍然想弄明白的是,如何使用References而不是Map来引用其他有自己映射的类型……
更新:引用的案例不幸更加复杂,请参考this Google Groups thread。简而言之:
// This won't work
foreach (var property in ExtendedProperties)
{
var prop = property;
part.Reference(dict => dict[part.Name]);
}
// This works but is not very dynamic
foreach (var property in ExtendedProperties)
{
var prop = property;
part.Reference<PropertyType>(dict => dict["MyProperty"]);
}这就是目前的情况。
发布于 2021-07-17 22:47:56
我也遇到了完全相同的问题。有了fluent nHibernate,我们无法映射这一点,但我自己却能以某种方式解决这个问题。我的解决方案是动态构建lambda表达式,并将其赋值为对象。例如,让我们这样说:
让我复制奥利弗引用的站点的一部分:
DynamicComponent(
x => x.Properties,
part =>
{
// Works
part.Map("Size").CustomType(typeof(string));
// Works
var keySize = "Size";
part.Map(keySize).CustomType(typeof(string));
// Does not work
part.Map(d => d[keySize]).CustomType(typeof(string));
// Works
part.References<Picture>(d => d["Picture"]);
// Does not work
var key = "Picture";
part.References<Picture>(d => d[key]);
});我们有一个问题,我们需要在映射中硬编码“图片”。但不知何故,在一些研究之后,我创建了以下解决方案:
var someExternalColumnNames = GetFromSomewhereDynamicColumns();
'x' is a DynamicComponent callback in fluent Nhibernate e.g. (DynamicColumns): DynamicComponent(a => a.DynamicColumns, x => (...content of method below...))
foreach(var x in someExternalColumnNames)
{
if (x.IsReferenceToPerson == true)
{
var param = Expression.Parameter(typeof(IDictionary), "paramFirst");
var key = Expression.Constant(x.Name);
var me = MemberExpression.Call(param, typeof(IDictionary).GetMethod("get_Item"), new[] { key });
var r = Expression.Lambda<Func<IDictionary, object>>(me, param);
m.References<Person>(r, x.Name);
}
else
{
m.Map(x.Name)
}
}
//
// Some class that we want to reference, just an example of Fluent Nhibernate mapping
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Table("Person");
Id(x => x.PersonId, "PersonId");
Map(x => x.Name);
}
}
public class Person
{
public virtual Guid PersonId { get; set; }
public virtual string Name { get; set; }
public Person()
{ }
}也许这会对你有所帮助
https://stackoverflow.com/questions/2834085
复制相似问题