首页 > 解决方案 > 使用 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>表中的每一列手动添加它们,即使它们具有与实体属性相同的名称?我是否缺少任何配置以使其自动映射?

谢谢你的时间。

标签: c#nhibernate

解决方案


原来我用错了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);
...

推荐阅读