1

我试图映射许多一对多的关系,但映射不起作用(列表属性保持为空,而不是存储的项目FluentNHibernate自动映射多对多

我用下表:

User(Id, Name, Password,...) 
Role(Id, Name) 
RoleUser(UserId, RoleId) with a compound primary key 

我的实体文件

public class User 
{ 
    public virtual int Id { get; protected set; } 
    public virtual string UserName { get; set; } 
    public virtual IList<Role> Roles { get; set; } 
} 
public class Role 
{ 
    public virtual int Id { get; protected set; } 
    public virtual IList<User> Users { get; set; } 
    public virtual string Name { get; set; } 
} 

但是也有一些应用了两个约定:

public class MyForeignKeyConvention : ForeignKeyConvention 
{ 
    protected override string GetKeyName(Member property, Type type) 
    { 
     return property == null ? type.Name + "Id" : property.Name + "Id"; 
    } 
} 
public class MyManyToManyConvention : IHasManyToManyConvention 
{ 
    public void Apply(IManyToManyCollectionInstance instance) 
    { 
     var firstName = instance.EntityType.Name; 
     var secondName = instance.ChildType.Name; 

     if (StringComparer.OrdinalIgnoreCase.Compare(firstName, secondName) > 0) 
     { 
      instance.Table(string.Format("{0}{1}", secondName, firstName)); 
      instance.Inverse(); 
     } 
     else 
     { 
      instance.Table(string.Format("{0}{1}", firstName, secondName)); 
      instance.Not.Inverse(); 
     } 

     instance.Cascade.All(); 
    } 
} 

当我的映射导出到文件,我得到用户定义中的下面的代码片段为例:

<id name="Id" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> 
    <column name="Id" /> 
    <generator class="identity" /> 
</id> 
<bag cascade="all" inverse="true" name="Roles" table="RoleUser"> 
    <key> 
    <column name="UserId" /> 
    <column name="UserId" /> 
    </key> 
    <many-to-many class="Security.Role, Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"&gt; 
    <column name="RoleId" /> 
    </many-to-many> 
</bag> 
<property name="UserName" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> 
    <column name="UserName" /> 
</property> 

关键中的重复列用户ID似乎不正确我。 我不确定我做错了什么。感谢帮助。

+0

does schemaexport生成正确的模式?您可以将ddl导出到文件而不是db – Firo 2013-05-13 10:03:48

+0

模式导出片段由方法ExportTo(folder)生成。 你是什么意思? – 2013-05-13 13:57:23

+0

你发布了生成的映射,但我想看到'新的SchemExport(config).Execute(新的StreamWriter(“somefile.txt”)。WriteLine,false,null,false)' – Firo 2013-05-13 20:22:02

回答

-1

问题在于映射表的模式。我结束了一个自定义的ManyToManyTableConvention。