将Nhibernate对象转换为JSON



转换时出现此错误。

正在初始化[Entity.Tag#8]-未能延迟初始化的集合角色:Entity.Tag.Feed,没有会话或会话关闭

Feed feed = new Feed();
Tag tag = Tag.READ.ById(8);
feed.Tag.Add(tag);
feed.Language = ENLanguage.EN;
feed.Name = "Foo";
feed.Save();
string x = JsonConvert.SerializeObject(feed);

进料类别

public class Feed : BaseClass<Feed>
{
    public virtual int FeedId { get; set; }
    public virtual IList<Tag> Tag { get; set; }
    public virtual ENLanguage Language { get; set; }
    public virtual string Name { get; set; }
    public Feed()
    {
        Tag = new List<Tag>();
    }
    public virtual void AddTag(Tag tag)
    {
        tag.Feed.Add(this);
        Tag.Add(tag);
    }
}

进料图

public class FeedMap : ClassMap<Feed>
{
    public FeedMap()
    {
        Id(x => x.FeedId);
        HasManyToMany(x => x.Tag).Cascade.All().Table("FeedTag");
        Map(x => x.Language).CustomType<short>();
        Map(x => x.Name);
    }
}

标签类

public class Tag : BaseClass<Tag>
{
    public virtual int TagId { get; set; }
    public virtual IList<Feed> Feed { get; protected set; }
    public virtual string Name { get; set; }
}

标签地图

public class TagMap : ClassMap<Tag>
{
    public TagMap()
    {
        Id(x => x.TagId);
        Map(x => x.Name);
        HasManyToMany(x => x.Feed).Cascade.All().Inverse().Table("FeedTag");
    }
}

保存方法

    using (var session = NHibernateHelper.OpenSession())
    {
        using (var transaction = session.BeginTransaction())
        {
            session.SaveOrUpdate(x);
            transaction.Commit();
        }
    }

听起来你的会话结束得太快了。你打开它只是为了保存。

尝试

using (var session = NHibernateHelper.OpenSession())
{
  Feed feed = new Feed();
  Tag tag = Tag.READ.ById(8);
  feed.Tag.Add(tag);
  feed.Language = ENLanguage.EN;
  feed.Name = "Foo";
  feed.Save();
  string x = JsonConvert.SerializeObject(feed);
}

我认为您的问题是没有初始化惰性集合当你从数据库中获取对象时,IList类的Feed标记

Tag.READ.ById(8); // in that method you have to initialize Feed

类似的东西

using(session = NHibernateHelper.OpenSession())
{
var TagObjectFromDb = session.Get<Tag>(id);
NHibernateUtil.Initialize(TagObjectFromDb.Feed);//initialize lazy collection, 
return TagObjectFromDb;
}

Feed fbfeed = new Feed();//fbfeed - typo?
Tag tag = Tag.READ.ById(8);
feed.Tag.Add(tag);//fbfeed - typo?

相关内容

  • 没有找到相关文章

最新更新