我read many posts这里有关标题中提到的异常。通常,此异常意味着我将字段映射到一个实体。我花了很多时间看着我的映射,但仍然找不到什么问题。能否帮助我理解这里做错了什么:
public class CustomerSegment : ModelEntity, IEntityDescriptor
{
public const string Standart = "Standard";
public virtual string Name { get; set; }
public virtual NetworkNHMapped Network { get; set; }
public virtual string GetDescriptor()
{
return Name;
}
}
public class CustomerSegmentMap : ClassMap<CustomerSegment>
{
public CustomerSegmentMap()
{
Table("NetworkProperty");
Id(x => x.Id).Column("NetworkPropertyId");
Map(x => x.Name).Column("PropertyName");
References(x => x.Network).Column("NetworkId");
}
}
}
当我尝试从DB获取所有CustomerSegment实体时发生异常。
其他实体的代码:
public class NetworkNHMapped : ModelEntity
{
[StringLength(50)]
public virtual string Name { get; set; }
public virtual int NetworkOwnerId { get; set; }
public virtual int NetworkTypeId { get; set; }
public virtual RepairShop.NetworkType NetworkType { get { return (RepairShop.NetworkType)NetworkTypeId; } }
}
public class NetworkNewMap : ClassMap<NetworkNHMapped>
{
public NetworkNewMap()
{
Table("Network");
Id(x => x.Id, "NetworkId");
Map(x => x.Name, "NetworkName");
Map(x => x.NetworkOwnerId, "NetworkOwnerId");
Map(x => x.NetworkTypeId, "NetworkType");
}
}
基础ModelEntity:
public virtual int Id { get; set; }
public override int GetHashCode()
{
if (!IsPersisted())
{
return base.GetHashCode();
}
unchecked
{
int result = GetObjectRealType(this).GetHashCode();
result = 42 * result + Id.GetHashCode();
return result;
}
}
public override bool Equals(object other)
{
if (ReferenceEquals(this, other))
{
return true;
}
if ((other == null) || !(other is ModelEntity))
{
return false;
}
var thisType = GetObjectRealType(this);
var otherType = GetObjectRealType(other);
if (thisType != otherType)
return false;
if (Id.Equals(default(long)) && (other as ModelEntity).Id.Equals(default(long)))
{
return base.Equals(other);
}
return Id == (other as ModelEntity).Id;
}
public static bool operator ==(ModelEntity entity1, ModelEntity entity2)
{
var obj1 = (object)entity1;
if (obj1 == null && ((object)entity2) == null)
return true;
return obj1 != null && entity1.Equals(entity2);
}
public static bool operator !=(ModelEntity entity1, ModelEntity entity2)
{
return !(entity1 == entity2);
}
public virtual bool IsPersisted()
{
return Id > 0;
}
protected static Type GetObjectRealType(object obj)
{
return (obj is INHibernateProxy) ? NHibernateUtil.GetClass(obj) : obj.GetType();
}
}
答案 0 :(得分:2)
我要做的第一件事是查看正在生成的XML文件,如果您有相同属性的重复映射,则会显示。
如果您正在使用NH和ModelMapper,那么只需拨打WriteAllXmlMapping
即可:例如: -
var mapper = new ModelMapper();
mapper.AddMappings(typeof(CmsMeta).Assembly.GetTypes());
//This will write all the XML into the bin/mappings folder
mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping();
如果您正在使用Fluent NHibernate,请查看此blog post以导出您的XML。
生成XML后我打赌你会发现重复的映射!否则请参阅此blog post,如果您正在向映射文件中的相关实体公开外键以及使用many-to-one
...,则可能会出现这种情况。如果是这种情况,请将insert =“false”和update =“false”添加到外键属性并再次运行。
无论哪种方式生成XML并查看,如果您看不到它将相关的XML文件发布到您的问题中,我们将会看一看。