现在的位置: 首页 > 综合 > 正文

ActiveRecord中Lazy属性的测试与问题

2018年03月19日 ⁄ 综合 ⁄ 共 2240字 ⁄ 字号 评论关闭
测试用的AR对象Blog和Post如下
[ActiveRecord()]
public class Blog
{
private Guid id;

[PrimaryKey(PrimaryKeyType.Assigned,
"ID")]
public Guid ID
{
get { return id; }
set { id = value; }
}

private IList post = new ArrayList();

[HasMany(
typeof(Post), ColumnKey = "Blog_ID", Table = "Post",
Cascade
= ManyRelationCascadeEnum.None, Lazy = true)]
public IList Post
{
get { return post; }
set { post = value; }
}
}

[ActiveRecord()]
public class Post
{
private Guid id;

[PrimaryKey(PrimaryKeyType.Assigned,
"ID")]
public Guid ID
{
get { return id; }
set { id = value; }
}

private string title;

[Property()]
public string Title
{
get { return title; }
set { title = value; }
}

private Blog blog;

[BelongsTo(
"Blog_ID")]
public Blog Blog
{
get { return blog; }
set { blog = value; }
}

}

测试一:

Guid id1 =Guid.NewGuid();
Guid id2
= Guid.NewGuid();
using (SessionScope scope = new SessionScope())
{
      Blog blog1 = new Blog();
      blog1.ID = id1;
      ActiveRecordMediator
<Blog>.Create(blog1);
      Post post
= new Post();
      post.ID
= id2;
      post.Blog
= blog1;
      ActiveRecordMediator<Post>.Create(post);
      Console.WriteLine(blog1.Post.Count);//输出0
      Blog blog2 = ActiveRecordBase.Find(id1);
      Console.WriteLine(blog2.Post.Count);//输出0
}
   using (SessionScope sc = new SessionScope())
   {
   Blog blog3 = ActiveRecordBase<Blog>.Find(id1);
   
Console.WriteLine(blog3.Post.Count);//输出1
   }

测试二:

   Guid id1 =Guid.NewGuid();
   Guid id2
= Guid.NewGuid();
   using (SessionScope scop = new SessionScope())
   {
      Blog blog1
= new Blog();
      blog1.ID
= id1;
      ActiveRecordMediator
<Blog>.Create(blog1);
   }
   using (SessionScope sc = new SessionScope())
    {
      Blog blog2
= ActiveRecordBase<Blog>.Find(id1);
      Post post
= new Post();
     post.ID
= id2;
      post.Blog
= blog2;
      ActiveRecordMediator
<Post>.Create(post);
      Console.WriteLine(blog2.Post.Count);//输出1
      /*********
      Post post2 = new Post();
      post2.ID = Guid.NewGuid();
      post2.Blog = blog2;
      Console.WriteLine(blog2.Post.Count);//输出1
      /*********
}

测试一:

说明在一个SessionScope里创建带有lazyload属性的对象同时又在这个SessionScope里读取时,lazeload的那个
属性读取的是脏数据,原因是在创建这个对象的时候已经将这个对象加到了AR的一级缓存,在这个SessionScope再读取时是读取的缓存对象.

测试二:

在这个过程中遇到的一个郁闷问题:跑测试2的时候,有时候输出的是1,有时候是0,找出规律是只要不调试都是输出1,一调试有时候输出1,有时候输出0,原因是在跟踪代码的时候,如下图,如果在 ActiveRecordMediator<Post>.Create(post);之前查看了Blog的Post属性的话,这个时候已经将该lazeload的属性从数据库读出来放到一级缓存里了,在这个SessionScope里面再读取的值都不会变化,所以出现"有时候输出的是1,有时候是0".加上"/****"之间的代码查看输出结果,①②都输出1再次证明这个结论.

抱歉!评论已关闭.