刚从 NHibernate 开始,在我看来一切似乎都是正确的,但显然不是。当我进行如下所示的单元测试时,我收到回信,关键字“User”附近存在语法错误,这是我的用户类:
namespace Users
{
public class User
{
public virtual string firstName { get; set; }
public virtual string lastName { get; set; }
public virtual int Id { get; set; }
}
}
和用户映射(也在列名周围没有方括号,结果相同:
namespace Users
{
class UserMap: ClassMap<User>
{
UserMap()
{
Table("User");
Id(x => x.Id).GeneratedBy.Native().Column("[Id]").Not.Nullable();
Map(x => x.firstName).Not.Nullable().Column("[firstName]");
Map(x => x.lastName).Not.Nullable().Column("[lastName]");
}
}
}
名为 Framework.cs 的配置文件
namespace Users
{
public class Framework
{
private const string ConnectionStr = "Data Source=ERALCH-ESTEPHEN;Initial
Catalog=NHDev;Integrated Security=True;Pooling=False";
public static ISessionFactory CreateFactory()
{
return Fluently.Configure()
.Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration
.MsSql2008
.ConnectionString(ConnectionStr))
.Mappings(x=>x.FluentMappings.AddFromAssemblyOf<User>())
.BuildSessionFactory();
}
}
}
数据访问层——简单地通过 Id 检索用户
namespace Users
{
public class Accesslayer
{
public static IList<User> GetUserById(int Id)
{
ISessionFactory provider = Framework.CreateFactory();
using (ISession session = provider.OpenSession())
{
return session.CreateSQLQuery(String
.Format("SELECT * FROM User WHERE Id={0}", Id)).List<User>();
}
}
}
}
最后是单元测试层
namespace Users
{
[TestFixture]
class AccessLayerTest
{
[Test]
public void CanGetUserById()
{
Assert.AreEqual(1, Accesslayer.GetUserById(1).Count());
}
}
}
数据库是 MSsql,其中包含一个表“用户”,其列与用户属性匹配。任何帮助将不胜感激谢谢