gpt4 book ai didi

c# - 在没有对象属性的情况下在 Fluent NHibernate 中映射外键

转载 作者:太空狗 更新时间:2023-10-29 21:50:40 25 4
gpt4 key购买 nike

我的问题是,是否存在不需要 Child 对象具有 Parent 对象属性的 Parent 和 Child 对象的 Fluent NHibernate 映射?我还没有想出如何将引用映射回父对象。当我按原样使用映射调用 Create 时,出现异常,因为子对象没有返回父对象所需的外键(数据存储中需要)。

我有两个 POCO 类:

public class Parent
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Child> Childs { get; set; }
}

public class Child
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual int ParentId { get; set; }
}

还有一些映射:

public class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
this.Table("Parents");
this.Id(x => x.Id);
this.Map(x => x.Name);
this.HasMany(x => x.Childs).KeyColumn("ChildId").Cascade.AllDeleteOrphan();
}
}

public class ChildMap : ClassMap<Child>
{
public ChildMap()
{
this.Table("Childs");
this.Id(x => x.Id);
this.Map(x => x.Name);
// Needs some sort of mapping back to the Parent for "Child.ParentId"
}
}

和创建方法:

public Parent Create(Parent t)
{
using (this.session.BeginTransaction())
{
this.session.Save(t);
this.session.Transaction.Commit();
}
return t;
}

我希望能够创建一个具有子对象列表的父对象,但不希望子对象具有返回到其父对象(父 ID 除外)的引用。我想这样做是为了避免从 Parent 到 Childs 列表的循环引用返回到 Parent 对象,因为这会导致 JSON 序列化问题。

最佳答案

你可以毫无问题地映射这些实体,试试这个:

public class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
this.Table("Parents");
this.Id(x => x.Id);
this.Map(x => x.Name);
this.HasMany(x => x.Childs).KeyColumn("ChildId").Cascade.AllDeleteOrphan();
}
}

public class ChildMap : ClassMap<Child>
{
public ChildMap()
{
this.Table("Childs");
this.Id(x => x.Id);
this.Map(x => x.Name);
this.Map(x => x.ParentId);
// if you have a reference of Parent object, you could map as a reference, for sample:
this.References(x => x.Parent).Column("ParentId");
}
}

当您从 ISession 获取实体时,不要将其序列化为某种格式,因为这些可能是 nhibernate 的代理而不是实体对象。尝试创建 DTO (Data Transfer Object) classes并将这些实体转换为 DTO 对象,并将其序列化。您将避免循环引用。例如:

public class ParentDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }

/* here you just have the primitive types or other DTOs,
do not reference any Entity type*/
}

当您需要读取值以共享序列化值时:

var dto = ISession.Query<Parent>()
.Select(x =>
new ParentDTO() {
Id = x.Id,
Name = x.Name,
ParentId = x.ParentId)
.ToList();

从数据访问层获取此结果并尝试序列化,例如:

var result = Serialize(dto);

关于c# - 在没有对象属性的情况下在 Fluent NHibernate 中映射外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626377/

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