我正在尝试映射多对多关系,但映射不起作用(列表属性保持为null且项目未存储。
我使用下表:
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">
<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似乎对我不正确。 我不确定我做错了什么。谢谢你的帮助。
答案 0 :(得分:-1)
问题是映射表的架构。我最终得到了一个自定义的ManyToManyTableConvention。