NhiberNate Map by code不包含'id'的定义

本文关键字:定义 id 包含 Map by code NhiberNate | 更新日期: 2023-09-27 18:16:35

我玩过NHiberNate,我让它与xml定义一起工作,但我被困在我的Map by Code测试中。我有以下代码:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using NHibernate.Mapping;

namespace NHibernatePets
{
public class Pet
{
    virtual public int id { get; set; }
    virtual public string PetName { get; set; }
    virtual public string Species { get; set; }
    virtual public DateTime Birthday { get; set; }
    virtual public string Speak()
    {
        return "Hi.  My name is '" + PetName + "' and I'm a " + Species    + " born on " + Birthday + ".";
    }
}
public class PetMap : ClassMapping<Pet>
{
    public PetMap()
    {
        table("Pet");
        Lazy(true);
        Id(x => x.Id, map => map.Generator(Generators.Identity));
        Property(x => x.Petname, map => map.NotNullable(true));
        Property(x => x.Species, map => map.NotNullable(true));
        Property(x => x.Birthday, map => map.NotNullable(true));
    }

当我按下f5时,它给我以下错误信息

错误15 'NHibernatePets。宠物'不包含'Id'的定义,也没有扩展方法'Id'接受类型为'NHibernatePets '的第一个参数。可以找到Pet(您是否缺少using指令或程序集引用?)}

我的计划是能够在PET数据库上执行如下查询

using (ISession session = OpenSession())
{
    IQuery query = session.CreateQuery(" FROM Pet");
    IList<Pet> pets = query.List<Pet>();
    Console.Out.WriteLine("pets.Count = " + pets.Count);
    pets.ToList().ForEach(p => Console.WriteLine(p.Speak()));
}

当我使用xml映射表时,它工作了。我哪里做错了?

NhiberNate Map by code不包含'id'的定义

c#是区分大小写的,因为ID属性命名为" id "

public class Pet
{
    virtual public int id { get; set; }

不能映射为Id

Id(x => x.Id... // there is no Id on x === Pet
因此,为了遵循c#中常见的命名约定,只需将属性名称更改为 Id
public class Pet
{
    //virtual public int id { get; set; }
    virtual public int Id { get; set; }