我有两个类User和Appointment,它们以前以多对多关系链接。但是现在我必须能够管理这种关系的状态(我需要能够跟踪用户是接受约会还是被拒绝还是尚未响应)。
这些类映射到各自的表“用户”和“约会”。 这两个表都是通过UserAppointments表连接的,该表具有复合主键,包括用户的fk和约会的fk。
当我尝试将新的UserAppointment对象添加到约会对象的集合中时,当前实现会引发异常消息:“ 此SqlParameterCollection的索引2无效,计数为2。” >
用户映射
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(d => d.Id);
Map(d => d.FirstName).Column("FirstName");
Map(d => d.LastName).Column("LastName");
Map(d => d.Email).Column("Email");
HasMany(u => u.UserAppointments);
Table("Users");
}
}
约会映射
public class AppointmentMap : ClassMap<Appointment>
{
public AppointmentMap()
{
Id(c => c.Id);
HasMany(a => a.AppointmentParticipants).Inverse().Cascade.All();
References(a => a.Location).Column("FkAddressId");
Map(a => a.DateAndTime).Column("AppointmentDate").CustomType<UtcDateTimeType>();
Map(a => a.Description).Column("AppointmentDescription");
Map(a => a.Status).Column("AppointmentStatus").CustomType<AppointmentStatus>();
HasMany(a => a.AppointmentEstates).Inverse().Cascade.All();
Table("Appointments");
}
UserAppointments映射
public class UserAppointmentsMap : ClassMap<UserAppointment>
{
public UserAppointmentsMap()
{
CompositeId()
.KeyReference(a => a.Appointment, "FkAppointmentsId")
.KeyReference(u => u.User, "FkUserId");
References(a => a.User).Column("FkUserId");
References(a => a.Appointment).Column("FkAppointmentsId");
Table("UserAppointments");
}
}
预期结果是,当我向现有约会的集合中添加新的UserAppointment时,将在UserAppointments表中创建一个指向相关User和Appointment实体的新记录
答案 0 :(得分:0)
我终于设法解决了这个问题。...实际上我的代码有几个问题:
“此Count = 2的SqlParameterCollection的无效索引2。” 的问题是由UserAppointmentsMap引起的。一旦将属性定义为组合键的一部分,就不应再次将其映射为引用。
public class UserAppointmentsMap : ClassMap<UserAppointment>
{
public UserAppointmentsMap()
{
CompositeId()
.KeyReference(a => a.Appointment, "FkAppointmentsId")
.KeyReference(u => u.User, "FkUserId");
Table("UserAppointments");
}
}
带有外键的复合ID应该使用KeyReference代替KeyProperty
我遇到了错误生成的查询的问题(外键错误,即不是FkAppointmentsId,而是在寻找Appointments_Id),所以我必须明确指定列名
public class AppointmentMap : ClassMap<Appointment>
{
public AppointmentMap()
{
Id(c => c.Id);
HasMany(a => a.AppointmentParticipants).Inverse().KeyColumn("FkAppointmentsId").Cascade.All();
References(a => a.Location).Column("FkAddressId");
Map(a => a.DateAndTime).Column("AppointmentDate").CustomType<UtcDateTimeType>();
Map(a => a.Description).Column("AppointmentDescription");
Map(a => a.Status).Column("AppointmentStatus").CustomType<AppointmentStatus>();
HasMany(a => a.AppointmentEstates).Inverse().KeyColumn("FkAppointmentsId").Cascade.All();
Table("Appointments");
}
}