gpt4 book ai didi

c# - 流利的 NHibernate : How to have a one-to-many reference in both directions?

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:34 24 4
gpt4 key购买 nike

我们的系统上有 UsersPersons。每个用户有很多人。但是当用户登录时,我们需要查找他的主要Person记录,填写他的姓名、地址、电话等。

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
}

类映射如何在没有循环引用的情况下查找它?

最佳答案

试试这个:

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() 上获得“对象引用未保存的 transient 实例”。

关于c# - 流利的 NHibernate : How to have a one-to-many reference in both directions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4495823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com