2011-08-29 15 views
5

Più particolarmente, c'è una classeMongoDB C# driver - Può un campo chiamato Id non essere Id?

class X { 
     .... 
     string Id { get; set; } 
} 

class Y : X { 
     ObjectId MyId { get; set; } 
} 

vorrei MyID sia un ID per Y, cioè essere mappata _ID.

È possibile?

ottengo un'eccezione dopo questo codice:

var ys = database.GetCollection("ys"); 
ys.InsertBatch(new Y[] { new Y(), new Y()}); 

L'eccezione: { "Gli 'myid' di classe 'MongoTest1.Y' non può usare elemento nome '_id' perché è già utilizzato da membro 'Id' "}

banco di prova completa:.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using MongoDB.Bson; 
using MongoDB.Bson.Serialization; 
using MongoDB.Driver; 

namespace MongoTest1 
{ 
    class X 
    { 
     public string Id { get; set; } 
    } 

    class Y : X 
    { 
     public ObjectId MyId { get; set; } 
    } 

    class Program 
    { 
     static Program() { 
      BsonClassMap.RegisterClassMap<X>(cm => 
      { 
       cm.AutoMap(); 
       cm.SetIdMember(cm.GetMemberMap(c => c.Id)); 
      }); 

      BsonClassMap.RegisterClassMap<Y>(cm => 
      { 
       cm.AutoMap(); 
       cm.SetIdMember(cm.GetMemberMap(c => c.MyId)); 
      }); 
     } 

     static void Main(string[] args) 
     { 
      var server = MongoServer.Create("mongodb://evgeny:[email protected]:27017/test"); 
      var database = server.GetDatabase("test"); 

      using (server.RequestStart(database)) 
      { 
       var ys = database.GetCollection("ys"); 
       ys.InsertBatch(
         new Y[] { 
          new Y(), new Y() 
         } 
        ); 
      } 
     } 
    } 
} 

Id di X deve essere una stringa.

risposta

9

La risposta alla tua domanda è "sì, ma ...".

E è possibile avere un elemento chiamato Id che è non mappato all'elemento _id. Ad esempio:

public class X { 
    [BsonId] 
    public ObjectId MyId; 
} 

public class Y : X { 
    public string Id; 
} 

Tuttavia, in una gerarchia di classi l'organo _id deve essere alla radice della gerarchia (in altre parole, tutti i membri della gerarchia devono concordare con lo stesso _id).

Problemi correlati