c# - 使用 NHibernate ClassMapping 自动将列映射到类属性
问题描述
我正在使用设置 NHibernate 5.2 在本地 SQLExpress 数据库上进行尝试。
我的Category
实体(顺便说一下,它是示例Northwind数据库)
public class Category
{
public virtual int CategoryID { get; set; }
public virtual string CategoryName { get; set; }
public virtual string Description { get; set; }
public virtual byte[] Picture { get; set; }
}
我的CategoryMap
public class CategoryMap : ClassMapping<Category>
{
public CategoryMap()
{
Table("Categories");
Id(x => x.CategoryID);
}
}
我的测试配置和查询
class Program
{
static void Main(string[] args)
{
Configuration config = new Configuration()
.DataBaseIntegration(db =>
{
db.ConnectionString = @"<my connection string>";
db.Dialect<MsSql2008Dialect>();
});
var mapper = new ModelMapper();
mapper.AddMappings(new List<Type> {
typeof(CategoryMap)
});;
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
config.AddMapping(mapping);
var sessionFactory = config.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
var categories = session.QueryOver<Category>().List<Category>();
};
}
}
但是,我注意到在我的测试查询中,只有CategoryID
字段被填充,其他字段为空(在数据库中,表中Categories
它们有值)。如果我添加更多Property(x => x.<field name>)
,CategoryMap
它们会按预期获得各自的值。
我的问题是:我是否必须为Property(x => x.<property name here>
表中的每一列手动添加它们,即使它们具有与实体属性相同的名称?我是否缺少任何配置以使其自动映射?
谢谢你的时间。
解决方案
原来我用错了ModelMapper
。我将其更改为ConventionModelMapper
只需要在类映射中指定表名即可。
我的新CategoryMap
public class CategoryMap : ClassMapping<Category>
{
public CategoryMap()
{
Tables("Categories");
Id(x => x.CategoryID);
// In db this column's type is image
// while the property type is byte[] so this explicit property map is needed
Property(x => x.Picture, m => m.Type(new BinaryBlobType()));
}
}
我的配置的一部分(在同一个 Program 类中,为简洁起见省略其余部分)
...
// Unlike ModelMapper, this mapper automatically maps class name -> table, property -> column
var mapper = new ConventionModelMapper();
mapper.AddMapping<CategoryMap>();
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
config.AddMapping(mapping);
...
推荐阅读
- javascript - Webauthn 适用于 Mac 但不适用于 Safari iOS
- elasticsearch - 弹性重新索引非常慢
- angular - Angular 应用程序在浏览器返回单击时跳过其中一个页面
- reactjs - React 中的可扩展表蚂蚁设计中缺少展开按钮
- javascript - 如何在 Node js 和 MongoDB 中插入数组
- python - __init__() 缺少 1 个必需的位置参数:'config'
- html5-canvas - Fabric.js:窗口大小调整问题
- node.js - UnhandledPromiseRejectionWarning:NodeJS 拉取请求不起作用
- ios - 应用内购买非消耗品与我完美合作,但不适用于苹果查看器
- python - 如何根据熊猫数据框中的过滤器进行分组并计算最大值