我在使用Nhibernate Map By Code映射字典时遇到了一些麻烦。 我想让我的课程多语言。所以为此我创建了一个字典,为每个LanguageCode保存适当的_i18n语言类。
映射似乎有效,但是如果我想获得一个带有语言字典的产品,那么它总是空的,我不知道为什么。
这是我的代码:
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();
}
答案 0 :(得分:2)
问题实际上是您的测试 - 您创建一个新产品(p1)并通过调用Save将其附加到会话,这会将p1与会话相关联,因此无论何时从同一会话中检索该产品,它都将返回相同的实例。这意味着当你执行session.QueryOver()。List()时,该列表将包含完全相同的p1实例 - 它不会创建新实例并从数据库中填充它。
您有两种选择: 1)明确地将Product_i18n实例添加到p1字典 2)在新会话中检索产品之前刷新并关闭会话
我建议您同时为您的测试做这两个选项,第一个选项是保持代码的一致性,第二个选项是测试其他会话是否正确检索数据。