开发者

NHibernate mapping error in legacy mapping

开发者 https://www.devze.com 2023-03-18 20:24 出处:网络
I\'ve inherited a large set of NHibernate mappings that live in an existing, functional application. I\'ve branched this application to develop some new features, and while I do so I\'m also extending

I've inherited a large set of NHibernate mappings that live in an existing, functional application. I've branched this application to develop some new features, and while I do so I'm also extending the testing infrastructure to allow for a more TDD-like approach. But now I've hit a wall in one of my integration tests...

I have a class with test data, which I insert prior to the integration test. In the method that inserts these, I get the following exception:

NHibernate.PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of Domain.Entities.Project ---> System.InvalidCastException: 开发者_开发问答Unable to cast object of type 'System.Object' to type 'Domain.Entities.ProjectModules'.

and I can't figure out why. I have two Project instances that I try to persist in the database on setup, both defined like this:

new Project("2023", "projeName", "projaddr")
{
    PrincipalOwner = UserOne, // UserOne and Office are other properties
    Office = Office,
    // I've tried just not instantiating this too - gave the same exception
    ProjectModules = new ProjectModules 
    {
        HasModuleOne = false,
        HasModuleTwo = false
    });
});

The (relevant part of the) Fluent NHibernate mapping looks like this:

Component(m => m.ProjectModules, c =>
{
    c.LazyLoad();
    c.Map(x => x.HasModuleOne)
        .Column("ModuleOne").Not.Nullable().Default("0");
    c.Map(x => x.HasModuleTwo)
        .Column("ModuleTwo").Not.Nullable().Default("0");
});


I've solved this - for some reason, NHibernate didn't like when the component mapping was specified inline in the mapping for Projects, but if I moved the mapping to a separate class ComponentMap<T> it worked. So I changed the problematic lines to

Component(p => p.ProjectModules);

and added the following class to my mappings assembly:

public class ProjectModulesMap : ComponentMap<ProjectModules>
{
    LazyLoad.Always();
    Map(pm => pm.ModuleOne);
    Map(pm => pm.ModuleTwo);
}

Then everything worked as I would have expected it to from the start.

0

精彩评论

暂无评论...
验证码 换一张
取 消