2011-08-29 15 views
5

Bardziej szczególnie, istnieje klasaMongoDB C# driver - Czy pole o nazwie Id nie może być identyfikatorem?

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

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

ja jak myid się identyfikator dla Y, to znaczy być odwzorowywane _id.

Czy to możliwe?

uzyskać wyjątek po tym kodzie:

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

Wyjątek: { "«myid»członek klasy«MongoTest1.Y»Nie można użyć nazwy elementu«_id», ponieważ jest już używany przez członkowskiego 'Id' "}

Pełna przypadek testowy.

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() 
         } 
        ); 
      } 
     } 
    } 
} 

X jest identyfikator musi być ciągiem.

Odpowiedz

9

Odpowiedź na twoje pytanie brzmi "tak, ale ...".

To jest można mieć element o nazwie ID, który się nie odwzorowany do elementu _id. Na przykład:

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

public class Y : X { 
    public string Id; 
} 

Jednak w hierarchii klas członek _id musi być u podstaw hierarchii (innymi słowy, wszyscy członkowie hierarchii muszą uzgodnić przy użyciu tego samego _id).

Powiązane problemy