使用流畅的nhibernate在关系表中配置一对0或1关系

时间:2011-02-02 11:39:02

标签: nhibernate fluent-nhibernate

以下是我的课程:

public class User {
    public virtual int Id { get; private set;}
    public virtual IList<Bike> { get; set;}
}

public class Bike {
    public virtual int Id { get; private set;}
    public virtual string color { get; set;}
}

public class Accident{
    public virtual int Id { get; private set;}
    public virtual User User{ get; set;}
    public virtual Bike Bike{ get; set;}
}

我的桌子

  • 用户:Id
  • 自行车:Id,颜色,用户(fk)
  • 意外:Id
  • AccdentOccurance:AccidentId,UserId,BikeId

事故可能与自行车(隐含于自行车用户)或用户有关,但与自行车无关。 我的问题是如何配置Accident ClassMap以使用AccidentOccurance表?

希望你能提供帮助。

1 个答案:

答案 0 :(得分:0)

Lets see if I can get this right so it is helpful to you.

1. On the 3rd line, you left out "Bike" for the name you are assigning the 
   relation to.
2. Lines 4, 10 & 11, you were missing the reverse mappings.
   I added them with the following assumptions:
     a. A user can ride more than 1 bike.
     b. A user can be in more than 1 accident.
     c. A bike can be involved in more than 1 accident.
     d. A bike can only be used by 1 user.
        If you need the bike to be able to be used by more than 1 user
        change line 10 to: public virtual IList<User> User { get; set;}
        This will give you a Many to Many relationship.
3. I would merge the tables Accident and AccidentOccurance into 1 table 
   "Accident". Since if you kept them separated, you are looking at a 1 to 1 
   relationship that does not offer any special benefits. With the vast 
   majority of all 1 to 1 relationships, it is best to merge the tables to 
   limit the SQL queries and speed up your queries on large tables.


public class User {
    public virtual int Id { get; private set;}
    public virtual IList<Bike> Bike { get; set;} // Modified
    public virtual IList<Accident> Accident { get; set;} // Added
}

public class Bike {
    public virtual int Id { get; private set;}
    public virtual string color { get; set;}
    public virtual User User { get; set;} // Added
    public virtual IList<Accident> Accident { get; set; } // Added
}

public class Accident{
    public virtual int Id { get; private set;}
    public virtual User User{ get; set;}
    public virtual Bike Bike{ get; set;}
}
相关问题