MongoDB:利用官方驱动改装为EF代码风格的MongoDB.Repository框架 三

本次改动的主要内容是实现MongoDB.Repository在MongoDB中建立索引。

建立索引主要使用MongoDB的官方驱动中EnsureIndex方法。

在MongoDB.Repository中建立一个BsonIndexAttribute,用以标识需要建立索引的属性。

    /// <summary>
    /// Indicates that this field or property should be index.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public class BsonIndexAttribute : Attribute
    {
    }

 

BsonIndexAttribute的机制是在注册全部实体类型后,在统一建立索引,所以需要在MongoDBRepository.RegisterMongoDBContext(new TestDBContext())之后进行MongoDBRepository.RegisterMongoIndex()操作。

编码演示如下:

    public class Student : Entity
    {
        [BsonIndex]
        public string Name { get; set; }
        public int Age { get; set; }
    }
        [TestFixtureSetUp]
        public void Setup()
        {
            MongoDBRepository.RegisterMongoDBContext(new TestDBContext());
            MongoDBRepository.RegisterMongoIndex();
        }

源码地址

 

 

 

posted on 2013-10-21 10:59  winhu  阅读(1510)  评论(0编辑  收藏  举报

导航