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。