0

我必须表格,表格人物和个人资料。Profile 的 Person 的 PK 为 FK。我也有两门课:

public class Person
{
  public int Id
  { 
    get;set;
  }

  public Profile Profile
  { 
    get;set;
  }
}

public class Profile
{
  Public int PersonId
  {
    get;set;
  }

Public string Language
  {
    get;set;
  }
}

我的映射是:

public class ProfileMap : ClassMap<Profile>
{

    public ProfileSettingsMap()
    {
        Id(x => x.PersonId).GeneratedBy.Assigned();
        Map(x => x.Language, "LanguageId");
    }
}

public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        HasOne(p => p.ProfileSettings).Cascade.All();
    }
}

现在,当更新现有的 Profile 对象时,它可以正常工作,但是当尝试插入新的 Profile 时,我得到:

无法执行批处理命令。[SQL: SQL 不可用]

PersonId is Profile 对象为0(调试时)

我怎样才能解决这个问题?

提前致谢

4

1 回答 1

0

您告诉 NH,您正在自己维护一对一 ( GeneratedBy.Assigned())

要么将其映射为onetoone

public class ProfileMap : ClassMap<Profile>
{

    public ProfileMap()
    {
        Id(x => x.PersonId).GeneratedBy.Foreign("Person"); // assuming you have a reference to Person in Profile
        Map(x => x.Language, "LanguageId");
    }
}

public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        HasOne(p => p.ProfileSettings).Cascade.All();
    }
}

或将配置文件映射为 Person 的组件

public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        Join("Profiles", join => 
        {
            join.Component(p => p.ProfileSettings, c =>
            {
                c.Map(x => x.LanguageId);
            });
        }
    }
}

更新:控制台应用程序中的此代码适用于 FNH 1.2

public class Person
{
    public virtual int Id { get; set; }
    public virtual Profile Profile { get; set; }
}

public class Profile
{
    public virtual int RecordsPerPage { get; set; }
}

public class PersonMap : ClassMap<Person>
{ 
    public PersonMap()
    { 
        Id(x => x.Id).GeneratedBy.Identity();
        Join("Profile", join =>
        {
            join.Component(p => p.Profile, c =>
            {
                c.Map(x => x.RecordsPerPage, "RecordsPerPage");
            });
        });
    }
}

static void Main(string[] args)
{
    var config = Fluently.Configure()
        .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
        .Mappings(m => m.FluentMappings.Add<PersonMap>())
        .BuildConfiguration();

    using (var sf = config.BuildSessionFactory())
    using (var session = sf.OpenSession())
    {
        new SchemaExport(config).Execute(true, true, false, session.Connection, null);

        using (var tx = session.BeginTransaction())
        {
            session.Save(new Person { Profile = new Profile { RecordsPerPage = 5 } });
            tx.Commit();
        }
    }
}
于 2012-05-03T06:41:40.933 回答