我们的系统上有用户和人员。每个用户都有很多人。但是当用户登录时,我们需要查找他的主要人员记录以填写他的姓名,地址,电话等。
public class Person
{
/// <summary>Every Person belongs to a user.</summary>
public virtual User User { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string Address { get; set; }
public virtual string Phone { get; set; }
// More methods & Properties
}
public class User : Entity
{
public virtual string Username { get; set; }
public virtual string Password { get; set; }
/// <summary>Every User has a primary person record.</summary>
public virtual Person PrimaryPerson { get; set; }
// More methods & Properties
}
如果没有循环引用,类映射如何查找?
答案 0 :(得分:4)
试试这个:
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Table("Persons");
Id(x =>x.Id, "PersonId").GeneratedBy.Identity();
References(x => x.User).Column("UserId").Cascade.All();
Map(x => x.FirstName, "FirstName");
Map(x => x.LastName, "LastName");
Map(x => x.Address, "Address");
Map(x => x.Phone, "Phone");
// More property maps
}
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.Id, "UserId").GeneratedBy.Identity();
Map(x => x.Username, "Username");
Map(x => x.Password, "Password");
References<Person>(x => x.PrimaryPerson).ForeignKey("PrimaryPersonId").Cascade.All();
}
}
这假设您的ID是自动编号,并且当您更新用户时,您还希望您的PrimaryPerson随之更新。如果不是这样,将Cascade.All()更改为Cascade.None()。请确保在执行此操作时,手动更新PrimaryPerson,或者如果不这样做,您将在SubmitChanges()上获得“对象引用未保存的瞬态实例”。
答案 1 :(得分:0)
根据我对你的问题的评论,我认为映射将是:
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Id(x => x.Id)...
...
References(x => x.User).Inverse(); // User references Person
}
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.Id)...
...
References(x => x.PrimaryPerson).Column("PrimaryPersonId")...
HasMany(x => x.People).KeyColumn("UserId").Inverse(); // UserId is on the Person
}
}
编辑:添加了表格结构。
[User]
UserId
... -- Other Columns
PrimaryPersonId -- FK to PersonId in Person table
[Person]
PersonId
... -- Other Columns
UserId -- FK to UserId in User Table for user has many Persons.