我进行了从 EF4 到 nHibernate 的转换,现在继承几乎没有问题。
我的实体和映射:
public class User
{
public virtual int Id { get; set; }
public virtual string UserName { get; set; }
}
public class Account
{
public virtual int Id { get; set; }
public virtual User User { get; set; }
}
public class Member : User
{
public virtual string SpecialPropForMember { get; set; }
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.Id);
Map(x => x.UserName);
}
}
public class AccountMap : ClassMap<Account>
{
public AccountMap()
{
Id(x => x.Id);
References(x => x.User);
}
}
public class MemberMap : SubclassMap<Member>
{
public MemberMap()
{
Map(x => x.SpecialPropForMember);
}
}
我通过的测试:
[Test]
public void TestMemberUserInheritence()
{
User newUser = new User()
{
UserName = RandomValues.String()
};
Member newMember = new Member()
{
SpecialPropForMember = "special"
};
Account newAccount = new Account()
{
User = newMember
};
Member member = account.User as Member;
Assert.IsNotNull(member);
}
和失败的测试:
[Test]
public void TestMemberUserInheritenceFromNHibernate()
{
User newUser = new User()
{
UserName = RandomValues.String()
};
UsersService().AddUser(newUser);
Member newMember = new Member()
{
SpecialPropForMember = "special"
};
MemberService().Add(newMember);
Account newAccount = new Account()
{
User = newMember
};
AccountService().Add(newAccount);
Account account; ;
using (var session = DataAccess.OpenSession())
{
account = session.Linq<Account>().First();
}
Member member = account.User as Member;
Assert.IsNotNull(member);
}
有人可以解释一下为什么 NH 不能正确解决继承问题吗?同样的问题适用于每个类的表和每个层次结构的表。