1

我正在尝试映射多对多关系,但映射不起作用(列表属性保持为空且不存储项目。

我使用下表:

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>

密钥中的重复列 UserId 对我来说似乎不正确。我不确定我做错了什么。感谢帮助。

4

1 回答 1

-1

问题是映射表的模式。我最终得到了一个自定义的 ManyToManyTableConvention。

于 2013-05-23T09:49:20.970 回答