[英]Get first element of many-to-many relationship
I am having some problems mapping one of my properties in nhibernate. 我在nhibernate中映射我的一个属性时遇到了一些问题。 I have a many-to-many relationship which is mapped to a collection. 我有一个多对多关系,映射到一个集合。 However, I also want to map a property to the first element of the many-to-many collection. 但是,我还想将属性映射到多对多集合的第一个元素。 Here is my code: The class I am mapping: 这是我的代码:我正在映射的类:
public class Project {
public Project() {
this.Addresses = new List<Address>();
}
public virtual int ID { get; set; }
public virtual IList<Address> Addresses { get; set; }
public virtual Address CurrentAddress { get; set; }
}
The classmap: 类图:
public class ProjectMap : ClassMap<Project> {
public ProjectMap() {
Table("Project");
Id(x => x.ID).GeneratedBy.Identity();
HasManyToMany(x => x.Addresses)
.Table("ProjectAddress")
.ParentKeyColumn("ProjectID")
.ChildKeyColumn("AddressID").Cascade.All();
}
But I need CurrentAddress to point to the first element of the Addresses property. 但我需要CurrentAddress指向Addresses属性的第一个元素。 So I tried to solve this with a getter that returns the first element like this: 所以我尝试使用getter来解决这个问题,它返回第一个元素,如下所示:
public virtual Address CurrentAddress {
get {
if (!Addresses.Any()) {
Address newAddress = new Address();
this.Addresses.Add(newAddress);
return newAddress;
}
else {
return this.Addresses.First();
}
}
}
However, when I try to query over the Project class currentaddress, I get a QueryException: could not resolve property: CurrentAddress. 但是,当我尝试查询Project类currentaddress时,我得到一个QueryException:无法解析属性:CurrentAddress。
This is obviously because the CurrentAddress property is not mapped in Nhibernate, but how can I fix this? 这显然是因为在Nhibernate中没有映射CurrentAddress属性,但是我该如何解决这个问题呢?
As you correctly pointed out, you can't query non-mapped properties, since NHibernate has no way to generate the appropriate SQL - the property's getter can be arbitrarily complex. 正如您正确指出的那样,您无法查询非映射属性,因为NHibernate无法生成适当的SQL - 属性的getter可能是任意复杂的。
There's no way to fix this, although you might have some luck exploring solutions like this: http://fabiomaulo.blogspot.cz/2010/07/nhibernate-linq-provider-extension.html 没有办法解决这个问题,虽然你可能会有一些运气来探索这样的解决方案: http : //fabiomaulo.blogspot.cz/2010/07/nhibernate-linq-provider-extension.html
However, I suggest querying the non-mapped properties in memory. 但是,我建议在内存中查询非映射属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.