2011-03-08 9 views
0

저는 NHibernate에 익숙하며 Fluent의 자동 매핑 기능을 사용하려고하므로 별도의 XML 파일을 손쉽게 관리 할 필요가 없습니다. 불행히도 참조 된 엔터티에 문제가 발생했습니다. 특히 'Fluent_NHibernate_Demo.Domain.Name.Id의 예외가 발생했습니다.'- System.Reflection.TargetException : 개체가 대상 형식과 일치하지 않습니다.Fluent NHibernate 관계 매핑 및 저장 예외

내 매핑 클래스 중 하나 이상에서 오류가있는 것으로 보입니다. 올바른 SQL (즉, 만들어진 테이블에 올바른 인덱스가 있음)을 생성하지만 오류가 발생했습니다. 내 도메인 모델과 매핑에 대한

구현은 다음과 같습니다


Name.cs

public class Name 
{ 
    public virtual int Id { get; protected set; } 
    public virtual string First { get; set; } 
    public virtual string Middle { get; set; } 
    public virtual string Last { get; set; } 
} 

Person.cs

public class Person 
{ 
    public virtual int Id { get; protected set; } 
    public virtual Name Name { get; set; } 
    public virtual short Age { get; set; } 
} 

NameMap.cs

public NameMap() 
{ 
    Table("`Name`"); 
    Id(x => x.Id).Column("`Id`").GeneratedBy.Identity(); 
    Map(x => x.First).Column("`First`").Not.Nullable().Length(20); 
    Map(x => x.Middle).Column("`Middle`").Nullable().Length(20); 
    Map(x => x.Last).Column("`Last`").Not.Nullable().Length(20); 
} 

PersonMap.cs 마지막

public PersonMap() 
{ 
    Table("`Person`"); 
    Id(x => x.Id).Column("`Id`").GeneratedBy.Identity(); 
    References<Name>(x => x.Name.Id, "`NameId`").Not.Nullable(); 
    // There's no exception if the following line is used instead of References 
    // although no constraint is created 
    // Map(x => x.Name.Id).Column("`NameId`").Not.Nullable(); 
    Map(x => x.Age).Column("`Age`").Nullable(); 
} 

예외 생성 할 다음 코드를

언급 한 바와 같이
Name name = new Name { First = "John", Last = "Doe" }; 
session.Save(name); 
Person person = new Person { Name = name, Age = 22 }; 
session.Save(person); // this line throws the exception 

, 생성 된 스키마는 정확하지만 위의 코드를 사용하여 저장할 수 없습니다입니다. Fluent NHibernate를 사용하여 외래 키 제약 조건을 만드는 올바른 방법은 무엇입니까?

답변

1

ID로 이름을 참조하려는 경우 그 작업을 수행해야합니다. NHibernate는 Person의 실제 FK 필드가 무엇인지, 어디에서 가리켜 야 하는지를 파악할만큼 똑똑하다. 즉 ORM이 수행하도록 설계된 작업입니다.

이 매핑보십시오 : 당신은 사람과 이름을 매핑 한

public PersonMap() 
{ 
    Table("`Person`"); 
    Id(x => x.Id).Column("`Id`").GeneratedBy.Identity(); 
    References(x => x.Name, "`NameId`").Not.Nullable();   
    Map(x => x.Age).Column("`Age`").Nullable(); 
} 

을; 결과적으로, NHibernate는 어떤 프로퍼티가 Name의 ID 프로퍼티인지 알고, Person의 외래 키를 생성하고 트래버스 할 수있다.

+0

Keith에게 감사드립니다. 솔루션이 완벽하게 작동합니다. –