Fluent Nhibernate: ignore interfaces/abstract clas

2019-08-21 14:37发布

Edit

I've got an interface that I'd like to base some classes on. When I go to BuildSchema (or UpdateSchema), Nhibernate creates a table for the interface. I thought I found a work-around as follows:

The Interface and Classes:

public interface ILevel
{
    int Id { get; set; }
    string Name { get; set; }
}
public abstract class Level : ILevel
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}
public class LevelOne : Level { }
public class LevelTwo : Level { }

The Mappings:

public class LevelMap : ClassMap<ILevel>
{
    public LevelMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
    }
}
public class LevelOneMap : SubclassMap<LevelOne>
{
}
public class LevelTwoMap : SubclassMap<LevelTwo>
{
}

This doesn't work (I did another UpdateSchema and the pesky ILevel table appeared).

Is there a configuration I'm unaware of to ignore interfaces/abstract classes altogether?

1条回答
女痞
2楼-- · 2019-08-21 14:45

For seperate tables LevelOne and LevelTwo, that both have the properties of Level/ILevel, use a generic mapping for Level:

public abstract class LevelMap<T> : ClassMap<T>
    where T : Level  // ILevel should work, too
{
    protected LevelMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
    }
}

public class LevelOneMap : LevelMap<LevelOne>
{
}

public class LevelTwoMap : LevelMap<LevelTwo>
{
}

You provide two separate class mappings without telling Fluent the real class hierarchy.

查看更多
登录 后发表回答