我在使用 Nhibernate Map By Code 映射字典时遇到了一些麻烦。我正在尝试使我的课程多语言。因此,为此我制作了一个字典,它为每个 LanguageCode 提供了适当的 _i18n LanguageClass。
映射似乎有效,但如果我想获得带有语言词典的产品,它总是为空,我不知道为什么。
这是我的代码:
public class Product
{
public virtual String ArticleNumber { get; set; }
public virtual Dictionary<String, Product_i18n> Languages { get; set; }
}
public class Product_i18n
{
public virtual long Id { get; set; }
public virtual Product Product { get; set; }
public virtual String LanguageCode { get; set; }
public virtual String Name { get; set; }
}
这是映射:
class ProductMap : ClassMapping<Product>
{
public ProductMap()
{
Lazy(true);
// Sets Tablename
Table("Prodcut");
// primary key
Id(product => product.ArticleNumber, mapping =>
{
mapping.Column("ArticleNumber");
mapping.Generator(Generators.Native);
});
Map<string, Product_i18n>(
product => product.Languages,
mapping =>
{
},
mapkey =>
{
mapkey.Element(k =>
{
k.Column("LanguageCode");
});
},
mapvalue =>
{
mapvalue.OneToMany();
});
}
}
class Product_i18n_Map : ClassMapping<Product_i18n>
{
public Product_i18n_Map()
{
/*ComposedId(mapper =>
{
mapper.Property(n => n.Product);
mapper.Property(n => n.LanguageCode);
});
* */
Table("Product_i18n");
Id(n => n.Id, mapper =>
{
mapper.Column("Product_i18nId");
mapper.Generator(Generators.Native);
});
Property(n => n.LanguageCode, mapping =>
{
mapping.Column("LanguageCode");
});
ManyToOne(n => n.Product, mapping =>
{
mapping.Column("Product");
});
Property(n => n.Name);
}
}
这就是我获取信息的主要功能:
Configuration config = new Configuration();
config.SessionFactory().GenerateStatistics();
config.DataBaseIntegration(Configure);
ModelMapper mapper = new ModelMapper();
mapper.AddMapping<Product_i18n_Map>();
mapper.AddMapping<ProductMap>();
config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
var lines = config.GenerateSchemaCreationScript(new MsSql2008Dialect());
foreach (var curLine in lines)
Console.WriteLine(curLine);
Console.WriteLine(Thread.CurrentThread.CurrentUICulture.IetfLanguageTag);
ISessionFactory factory = config.BuildSessionFactory();
using (ISession session = factory.OpenSession())
{
Product p1 = new Product() { ArticleNumber = "4711" };
session.Save(p1);
Product_i18n p1ger = new Product_i18n() { LanguageCode = "de-DE", Name = "Playstation", Product = p1 };
Product_i18n p1jap = new Product_i18n() { LanguageCode = "JP", Name = "プレイステーション", Product = p1 };
session.Save(p1ger);
session.Save(p1jap);
var query = session.QueryOver<Product>().List();
var query2 = session.QueryOver<Product_i18n>().List();
session.Close();
}