天道酬勤,学无止境

Fluent NHibernate - HasOne With Where Clause

with Fluent NHibernate i can map a one to many relationship against my User class by saying:

HasMany(x => x.Membership)
    .KeyColumn("UserID")
    .Where("Deleted = 0");

This works as expected that it only grabs the Membership records which have not been deleted. No say i have a field called Latest against the Membership where i know this would return one record per user, i'd like to be able to say:

HasOne(x => x.CurrentMembership)
    .Where("Current = 1");

But there is no Where method. I know i could do this in code by saying:

public virtual Membership CurrentMembership
    { get { return Membership.Single(m => m.Current); } }

But this doesn't allow me to do LINQ queries against this property. I'd just accepted this as a limitation in the past but it really is starting to bite me in terms of performance.

I'd really appreciate it if someone could help.

评论

Are you sure you mean "HasOne" and not a many-to-one ("References")?

http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/

HasOne(x => x.CurrentMembership)
    .Where("Current = 1");

If an entity has a "HasOne" relationship to another, then there is only one thing it can link to so a Where method doesn't make sense. If your code accidentally doesn't update the old membership to have Current=0, then there will be 2 instances of CurrentMembership that it could link to and you'd be pretty screwed.

I think that you have a problem in your database design. The best way that I can think of implementing this is is to have a CurrentMembershipID on your User table and then you can link directly to it with a HasOne. This is less overhead for your database (you don't have to store a Current column on your membership table) and it will effectively do what you're looking for. Also, it avoids a user having more than one membership having current set to 1.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • HasOne vs References Mapping Fluent NHibernate
    This is the first time I am working with FluentNhibernate Mapping and facing a question of how to reference another table. Any help is appreciated: I have several tables named CD_varname and all these contain two columns - CODE and DESCR. I have one main table called Recipient and it has, say two columns, called ALIVE and SEX, both are of type number, and they reference to the tables CD_ALIVE and CD_SEX. If Alive=1 in the Recipient, then we need to get the code and descr from CD_ALIVE table where Code=1. I have described a Codef class: public Class Codef { int Code { get; set; } string Descr {
  • HasOne vs References Mapping Fluent NHibernate(HasOne vs References Mapping Fluent NHibernate)
    问题 这是我第一次使用 FluentNhibernate Mapping 并面临如何引用另一个表的问题。 任何帮助表示赞赏: 我有几个名为 CD_ varname 的表,所有这些表都包含两列 - CODE 和 DESCR。 我有一个名为Recipient 的主表,它有两列,名为 ALIVE 和 SEX,都是数字类型,它们引用表 CD_ALIVE 和 CD_SEX。 如果 Recipient 中的 Alive=1,那么我们需要从 CD_ALIVE 表中获取 Code 和 descr,其中 Code=1。 我已经描述了一个 Codef 类: public Class Codef { int Code { get; set; } string Descr { get; set; } } 我的接收者类将这些分配给一个组件。 接收者类如下所示: public Class IRecepient { int ID { get; set; } Birth Birth {get; set;} Death Death { get; set; } } 我的出生和死亡课程在哪里: public Class Birth { DateTime BDate { get; set; } Codef Sex { get; set; } Codef Ethnicity { get; set; } //CD
  • fluent nhibernate HasOne WithForeignKey not working
    Whenever I load a Task class, the Document property is always null, despite there being data in the db. Task class: public class Task { public virtual Document Document { get; set; } Task Mapping override for AutoPersistenceModel: public void Override(AutoMap<Task> mapping) { mapping.HasOne(x => x.Document) .WithForeignKey("Task_Id"); As you can see form what NHProf says is being run, the join condition is wrong, the WithForeignKey doesnt seem to take effect. In fact, i can write any string in the above code and it makes no difference. FROM [Task] this_ left outer join [Document] document2_ on
  • How to do a fluent nhibernate one to one mapping?
    How do I do this I am trying to make a one to one mapping. public class Setting { public virtual Guid StudentId { get; set; } public virtual DateFilters TaskFilterOption { get; set; } public virtual string TimeZoneId { get; set; } public virtual string TimeZoneName { get; set; } public virtual DateTime EndOfTerm { get; set; } public virtual Student Student { get; set; } } // class map public SettingMap() { /// Id(Reveal.Member<Setting>("StudentId")).GeneratedBy.Foreign("StudentId"); //Id(x => x.StudentId); Map(x => x.TaskFilterOption).Default(DateFilters.All.ToString()).NvarcharWithMaxSize()
  • Fluent NHibernate 一对一映射(Fluent NHibernate One-to-One mapping)
    问题 我真的很难用 Fluent NHibernate 来利用 HasOne 映射。 基本上,A 类可以在 B 类中具有匹配(只有一个或没有)记录。 请帮助定义关系的 AMap 和 BMap 类。 谢谢你。 public class A { public virtual int Id {get;set;} public virtual string P1 {get;set;} public virtual string P2 {get;set;} public virtual string P3 {get;set;} } public class B { public virtual int Id {get;set;} public virtual string P4 {get;set;} public virtual string P5 {get;set;} public virtual string P6 {get;set;} } 回答1 要使one-to-one映射工作,您需要按照下面的代码将B类型的属性添加到A类,反之亦然。 这两个类都需要这些引用,因为 NHibernate 不支持单向一对一。 public class A { public virtual int Id {get;set;} public virtual string P1 {get;set;}
  • Fluent Nibernate 在映射中放置一个 where 子句(Fluent Nibernate putting a where clause in the mapping)
    问题 我有两个对象,一个父项和一个子项列表。 在我为父级流畅的 nhibernate 映射中,我想加载子级列表。 但是我希望这是有条件的,子表中的一列称为“IsDeleted”,我只想返回“IsDeleted”为假的子项。 是否可以设置映射来执行此操作? 如果不是,是否可以仅在标准 nhibernate 中进行? 谢谢 回答1 是的,您可以使用 Fluent NHibernate 中的 Where 约束来映射它。 有点像: HasMany(x => x.Children).Where("IsDeleted = 0"); Where 约束应该使用 SQL 语法而不是 HQL。 对于允许软删除的表,映射一个过滤掉已删除记录的视图可能更容易。
  • Fluent NHibernate 多态映射挑战(Fluent NHibernate Polymorphic Mapping Challenges)
    问题 我在使用 Table Per Concrete 类在 Fluent Nhibernate 中映射以下场景时遇到了一些问题: 假设我有以下类定义: public class Reading { .... } public class CarReading : Reading { .... } public class TruckReading : Reading { .... } public class Alert { .... public virtual Reading AReading { get; set; } } 所以我的问题是如何为 Alert 创建映射类,如果它与读取类(可以是卡车读取或汽车读取)具有一对一的关系,并指示 nhibernate 知道从哪个表加载数据(TruckReading 表或汽车阅读表) public class AlertMap : ClassMap<Alert> { .... HasOne(x => x.AReading); } 如果有人能指出我正确的方向,我将不胜感激。 谢谢。 回答1 public class AlertMap : ClassMap<Alert> { .... ReferenceAny(x => x.AReading) .EntityIdentifierColumn("readingid")
  • Fluent NHibernate Polymorphic Mapping Challenges
    I am having some problems mapping the following scenario in Fluent Nhibernate using Table Per Concrete class: Let's say I have the following class definitions: public class Reading { .... } public class CarReading : Reading { .... } public class TruckReading : Reading { .... } public class Alert { .... public virtual Reading AReading { get; set; } } So my question is how to create the mapping class for Alert, if it has a one to one relationship with reading class (could be either truck reading or car reading) and instruct nhibernate to know which table to load the data from (TruckReading table
  • Fluent NHibernate One-to-One mapping
    I am having a really hard time exploiting HasOne mapping with Fluent NHibernate. Basically, the class A can have a matching (only one or none) record in the class B. Please help with the AMap and BMap classes that define the relationships. Thank you. public class A { public virtual int Id {get;set;} public virtual string P1 {get;set;} public virtual string P2 {get;set;} public virtual string P3 {get;set;} } public class B { public virtual int Id {get;set;} public virtual string P4 {get;set;} public virtual string P5 {get;set;} public virtual string P6 {get;set;} }
  • NHibernate 一对一关系(NHibernate One-To-One Relationship)
    问题 我有以下Domain Model(s) : public class WriteOffApprovalUser { public virtual string UserName { get; set; } public virtual Employee Employee { get; set; } } public class Employee { public virtual string EmployeeID { get; set; } public virtual string EmployeeStatusCode { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual string PreferredName { get; set; } public virtual string JobTitle { get; set; } public virtual string Division { get; set; } public virtual string Department { get; set; } public virtual string Location { get; set
  • Fluent Nibernate putting a where clause in the mapping
    I've got two objects a parent and a child list. In my fluent nhibernate mapping for the parent I want to load the list of the children. However I want this to be conditional, a column in the child table is called "IsDeleted" and I only want to return the children where "IsDeleted" is false. Is it possible to set up a mapping to do this? If not is it possible to do it in just standard nhibernate? Thanks
  • Fluent NHibernate: How to create circular one-to-one mapping?
    public class AdminUser { public virtual int Id { get; set; } public virtual string UserName { get; set; } public virtual string Password { get; set; } public virtual bool IsLocked { get; set; } public virtual AdminUser Creator { get; set; } public virtual DateTime CreationDate { get; set; } } public class AdminUserMapping : ClassMap<AdminUser> { public AdminUserMapping() { Id(c => c.Id).GeneratedBy.Native(); Map(c => c.UserName).Not.Nullable(); Map(c => c.Password).Not.Nullable(); Map(c => c.IsLocked).Not.Nullable(); Map(c => c.CreationDate).Not.Nullable(); //HasOne<AdminUser>(... ?) } } Hi i
  • 一对一映射不适用于二级缓存(one-to-one mapping is not working with 2nd-Level-Cache)
    问题 我已经声明了 NHibernate3 的空闲映射: 使用 FluentNHibernate public class ActivityMap : ClassMap<Activity> { public ActivityMap() { this.Table("Activity"); this.Cache.ReadWrite(); this.Version(x => x.ObjectVersion); this.Id(x => x.Id).GeneratedBy.Assigned(); // snipp this.HasOne(x => x.AppointmentRecurrence).Cascade.Delete(); } } public class AppointmentRecurrenceMap : ClassMap<AppointmentRecurrence> { public AppointmentRecurrenceMap() { this.Table("AppointmentRecurrence"); this.Cache.ReadWrite(); this.Version(x => x.ObjectVersion); this.Id(x => x.Id).GeneratedBy.Foreign("Activity"); // snipp this.HasOne
  • 如何将 Fluent NHibernate Automapping 与实体中的多个相同类型的列表一起使用?(How can I use Fluent NHibernate Automapping with multiple Lists of the same type in an Entity?)
    问题 NHibernate 似乎不能自动映射一个实体中给定类型的多个 IList。 考虑以下两个实体(基于 Fluent NHibernate 源代码中包含的 Examples.FirstProject 示例代码)。 public class Employee { public virtual int Id { get; private set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } } public class Store { public virtual int Id { get; private set; } public virtual IList<Employee> Staff { get; set; } public virtual IList<Employee> Managers { get; set; } } 这似乎是一个完全有效的对象模型——每家商店都有几个员工和几个经理员工。 但是当我自动映射时,Staff 和 Managers 列表存储在 Employee 表中,所有这些都具有相同的外键。 Employee Table Id FirstName LastName Store_id 3 Daisy Harrison
  • NHibernate:CreateCriteria 和 Exists 子句(NHibernate: CreateCriteria and Exists clause)
    问题 如何使用 CreateCriteria 编写以下 SQL: SELECT * FROM FooBar fb WHERE EXISTS (SELECT FooBarId FROM Baz b WHERE b.FooBarId = fb.Id) 回答1 您可以这样做: var fooBars = Session.CreateCriteria<FooBar>() .Add(Restrictions.IsNotEmpty("Bazs")).List<FooBar>(); ...假设在 FooBar 对象中有一个集合属性(一对多)“Bazs”。 或者,您可以使用这样的分离标准: DetachedCriteria dCriteria = DetachedCriteria.For<Baz>("baz") .SetProjection(Projections.Property("baz.FooBarId")) .Add(Restrictions.EqProperty("baz.FooBarId", "fooBar.Id")); var fooBars = Session.CreateCriteria<FooBar>("fooBar") .Add(Subqueries.Exists(dCriteria)).List<FooBar>(); 回答2 刚刚解决了一个相关问题并最终得出了一个解决方案
  • Fluent NHibernate entity HasMany collections of different subclass types
    So everything is working well with the basic discriminator mapping. I can interact directly with entities A and B without any problems. public class BaseType {} public class EntityA : BaseType {} public class EntityB : BaseType {} This maps without drama in the BaseType mapping as DiscriminateSubClassesOnColumn<string>("Type") .SubClass<BaseType>("A", m => { }) .SubClass<BaseType>("B", m => { }); The problem occurs when: in an aggregate we want to map collections to each subclass Using mapping like below public class AggregateMap: BaseMap<Aggregate> { public AggregateMap() { HasMany<EntityA>(x
  • 您如何自动映射列表或与Fluent NHibernate一起使用float []?(How do you automap List<float> or float[] with Fluent NHibernate?)
    问题 成功完成示例程序的工作后,我现在开始使用Fluent NHibernate进行Real Work-尝试在项目的类层次结构上使用自动映射。 这是一个科学仪器应用程序,我映射的类具有几个属性,这些属性是浮点数的数组,例如 private float[] _rawY; public virtual float[] RawY { get { return _rawY; } set { _rawY = value; } } 这些数组最多可以包含500个值。 我没想到自动映射可以在数组上工作,但是无论如何都尝试过,但最初取得了一些成功。 每个数组都自动映射到BLOB(使用SQLite),这似乎是一个可行的解决方案。 当我尝试在包含数组的对象上调用SaveOrUpdate时,出现了第一个问题-我遇到了“对于float []没有持久性”异常。 因此,我的下一个想法是将我所有的阵列都转换为ILists,例如 public virtual IList<float> RawY { get; set; } 但是现在我得到了: NHibernate.MappingException: Association references unmapped class: System.Single 由于自动映射可以处理复杂对象的列表,因此对我而言从来没有发生过,因此它无法映射基本类型的列表。
  • nhibernate 中的 HasOne 和 References 有什么区别?(What are the differences between HasOne and References in nhibernate?)
    问题 nhibernate 中的HasOne()和References()什么区别? 回答1 HasOne为您创建表之间的一对一映射。 References创建了典型的多对一关系。 更多定义: 一对一关系意味着当一个表中存在一个记录时,它必须(或可以)在另一个被引用的表中具有一个且最多一个记录。 示例:用户表和选项表(一个用户有一组固定的选项) 多对一关系是指当一张表中存在一条记录时,另一张表中可以有许多相关记录。 示例:用户表和购买表(一个用户可以进行多次购买)。 注意:在我说table 的地方,您可以根据需要安全地用类或实体替换它,当使用 FluentNH 时,很容易互换使用它们。 这在 fluentnhibernate wiki 文章中有更准确的解释。
  • 是否可以使用 NHibernate 过滤器来过滤引用?(Is it possible to use NHibernate Filters to filter through references?)
    问题 人为的例子,但假设我有这些实体: public class Root { public virtual Customer Customer { get; set; } } public class Customer { public virtual CustomerData Data { get; set; } } public class CustomerData { public virtual string FooName { get; set; } } 现在,假设我想根据 FooName 的值为 Root 创建一个过滤器。 直觉上,我在我的 FooMap 类中尝试了这个。 使用 Fluent 映射。 ApplyFilter("FooNameFilter", "Customer.Data.FooName in (:argument)"); 这不起作用。 抛出 SqlClient.SqlException 说明The multi-part identifier "Customer.Data.FooName" could not be bound. 有没有办法让过滤器以这种方式工作,还是我被迫将该逻辑移到所有Query<Root>() ? 回答1 可行的是,如果可能,将filter移动到CustomerData对象,或者创建应用于Customer映射的“更复杂的 SQL
  • 如何在流利的NHibernate中加入表(How to join table in fluent nhibernate)
    问题 我们如何做到这种映射却又流利呢? <class name="Person" table="People"> <id name="Id"> <generator class="identity"/> </id> <property name="Name" /> <join table="Addresses"> <key column="PersonId"/> <property name="Line1"/> <property name="Line2"/> <property name="City"/> <property name="Country"/> <property name="ZipCode"/> </join> </class> 我知道我可以使用“参考”,但是我不需要相关表中的所有列。 我只需要一个财产。 回答1 帕科说的话不对。 这可以在Fluent NHibernate中完成。 我自己上网搜索了很长时间,找不到任何人在谈论这个选项,所以我只是和FNHibernate玩了一会儿,最后设法做到了。 这是我的情况: 我有两个桌子- "FormFields" => Columns { "FieldId", "FieldName", "FieldType", "DisplayOrder" } "FormStructure" => Columns { "FormId",