Skip to main content
 首页 » 编程设计

c#之如何使用 Fluent NHibernate 映射包含与父类型相同类型的实体的列表

2024年02月20日14wayfarer

我有一个这样的实体

public class Person 
{ 
    public virtual int Pkey { get; set; } 
    public virtual string Name { get; set; } 
 
    public List<Person> Friends{ get; set; } 
} 

它的表信息是这样的

create table Person 
( 
    PKey int not null IDENTITY, 
    Name varchar (20), 
    primary key (PKey) 
) 

为了获取好友列表,我正在维护另一个这样的表

Create table Friends 
( 
     PKey int not null IDENTITY, 
     PersonFKey int not null Foreign key references Person(PKey), 
     FriendFKey int not null Foreign key references Person(PKey) 
) 

现在当我像下面那样做映射时,我得到了一些错误(因为映射问题)

 public class PersonMap :  ClassMap<Person> 
 { 
    public PersonMap() 
    { 
        Id(x => x.Pkey); 
        Map(x => x.Name); 
        HasManyToMany(x => x.Friends).Cascade.All().Table("Friends").ParentKeyColumn("PersonFKey"); 
    } 
 } 

抛出的异常是,

FluentConfigurationException: "An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail." 

有内部异常(exception),

InvalidProxyTypeException: The following types may not be used as proxies: 
 
FluentNhibernateLearning.Entities.Person: method get_Friends should be 'public/protected virtual' or 'protected internal virtual' 
FluentNhibernateLearning.Entities.Person: method set_Friends should be 'public/protected virtual' or 'protected internal virtual' 

任何人都可以帮我指出我缺少的东西吗?

请您参考如下方法:

您没有说明错误是什么并且映射与类不匹配,但我认为问题在于您缺少 ChildKeyColumn 声明。在多对多映射中,您必须声明父键列和子键列;父键是包含集合的类的主键,子键是集合中类的主键。

此外,您几乎不希望对多对多进行级联,因为这会导致删除删除所有相关实体。也就是说,删除一个人会删除他所有的 friend 。

 public class IntermediaryMap :  ClassMap<Intermediary> 
 { 
    public IntermediaryMap() 
    { 
        Id(x => x.Pkey); 
        Map(x => x.Name); 
        HasManyToMany(x => x.SubBrokers).Table("Intermediary2SubBroker") 
            .ParentKeyColumn("IntermediaryFKey") 
            .ChildKeyColumn("SubBrokerFKey") 
            .AsSet(); 
    } 
 }