gpt4 book ai didi

nhibernate - Fluent NHibernate 以智能方式映射 IDictionary

转载 作者:行者123 更新时间:2023-12-04 20:22:50 24 4
gpt4 key购买 nike

鉴于这些类:

using System.Collections.Generic;

namespace FluentMappingsQuestion
{
public class Entity
{
public virtual int Id { get; set; }
public virtual IDictionary<string, Property> Properties { get; set; }
}

public class Property
{
public virtual Entity OwningEntity { get; set; }
public virtual string Name { get; set; }
public virtual int Value { get; set; }
public virtual decimal OtherValue { get; set; }
}
}

我如何使用 NHibernate(最好是流畅的风格)映射它们,以便这样做是可能的:
[Test]
public void EntityPropertyMappingTest()
{
using (var session = _factory.OpenSession())
{
var entity = new Entity();

// (#1) I would *really* like to use this
entity.Properties["foo"] = new Property { Value = 42, OtherValue = 42.0M };

session.Save(entity);
session.Flush();

// (#2) I would like the entity below to "update itself"
// on .Save or .Flush. I got it to work with .Load()
Assert.AreEqual(42, entity.Properties["foo"].Value);
Assert.AreEqual(42.0M, entity.Properties["foo"].OtherValue);
Assert.AreEqual("foo", entity.Properties["foo"].Name);
Assert.AreEqual(entity, entity.Properties["foo"].Owner);
}
}

我几乎设法通过这些映射做到了这一点:
// class EntityMap : ClassMap<Entity>
public EntityMap()
{
Id(x => x.Id);
HasMany(x => x.Properties)
.Cascade.AllDeleteOrphan()
.KeyColumn("EntityId")
.AsMap(x => x.Name);
}

// class PropertyMap : ClassMap<Property>
public PropertyMap()
{
Id(x => x.Id);
References(x => x.OwningEntity).Column("EntityId");
Map(x => x.Name).Length(32);
Map(x => x.Value);
{

我遇到的问题:
  • 如果我做 Entity.Properties .Inverse() ,它开始崩溃
  • 如果我不成功 .Inverse()然后 NHibernate 执行:INSERT(Entity), INSERT(Property), UPDATE(Property)而不仅仅是 INSERT(Entity), INSERT(Property)
  • 如果我做 Property.Name .Not.Nullable() ,它开始崩溃
  • 如果我不成功 .Not.Nullable() , 我的数据库架构中有一个洞

  • 我应该如何更改我的映射?

    最佳答案

    我通过指定这个映射来解决这个问题:

    HasMany<Property>(Reveal.Member<Entity>("InternalProperties"))
    .AsMap(p => p.Name)
    .Cascade.AllDeleteOrphan()
    .Inverse();

    并创建两个 IDictionary<string, Property> 类型的属性: PropertiesInternalProperties .第一个是第二个的代理字典,处理设置 OwningEntityName Property 的属性条目。

    关于nhibernate - Fluent NHibernate 以智能方式映射 IDictionary<string, class>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4564211/

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