Mongodb c#驱动程序不返回新的Id并且未设置默认值

时间:2014-05-30 00:11:34

标签: c# mongodb serialization

在下面的代码中,我有两个问题。

  
      
  1. Insert方法不返回Id属性。
  2.   
  3. 未设置我设置为datetime属性的默认值。
  4.   

我错过了什么?

以下是代码:

// I have an Application class:

internal class Applications
    {
        public string Id { get; set; }
        public string ApplicationName { get; set; }
        public string ApplicationNameLower { get; set; }
        public DateTime CraetionDate { get; set; }
    }

// I want to keep my class as "clean" as possible so I use a BsonClassMap like this

public void MapStart()
{
BsonClassMap.RegisterClassMap<Applications>(c =>
                {
                    c.AutoMap();
                    c.SetIgnoreExtraElements(true);
                    c.SetIdMember(c.GetMemberMap(a => a.Id));
                    c.GetMemberMap(a => a.Id).SetRepresentation(BsonType.ObjectId).SetIgnoreIfNull(true);
                    c.GetMemberMap(a => a.ApplicationName).SetElementName("ap");
                    c.GetMemberMap(a => a.ApplicationNameLower).SetElementName("apl");
                    c.GetMemberMap(a => a.CraetionDate).SetElementName("cd").SetDefaultValue(new DateTime(2001,2,21));
                });
}

// I have a helper method to return a collection:

private static MongoCollection<Applications> ApplicationsDb
        {
            get
            {
                MongoClient mongoClient = new MongoClient(_connectionString);
                MongoServer mongoServer = mongoClient.GetServer();
                MongoDatabase db = mongoServer.GetDatabase("mydbname");
                return db.GetCollection<Applications>("apps");
            }
        }


//I have an insert method:

private Applications CreateApplication(string applicationName)
        {
            Applications app = new Applications()
            {
                ApplicationName = applicationName,
                ApplicationNameLower = applicationName.ToLower()
            };

            try
            {
                WriteConcernResult wcResult = ApplicationsDb.Insert(app);
            }
            catch (Exception)
            {

                throw;
            }

            return app;
        }

1 个答案:

答案 0 :(得分:0)

1)insert方法不返回ID属性,因为它显然返回了WriteConcernResult。 (这假设您的示例代码已编译。)由于Insert方法是在驱动程序框架中定义的,因此您无法对其进行更改。

2)你在哪里打电话给MapStart()

3)永远不要这样做:

catch (Exception)
{
    throw;
}

它只用于清除堆栈跟踪,破坏可能对诊断问题有用的信息。