2014-11-11 18 views
10

Tôi nhận lỗi "Cannot deserialize string from BsonType ObjectId" trong khi cố gắng để có được tất cả các bản ghi từ MongoDB trong C# WebAPIKhông thể deserialize chuỗi từ BsonType ObjectId trong MongoDB C#

Id của tôi là

[BsonId] 
public string Id { get; set; } 

Sau khi thay đổi nó để

[BsonRepresentation(BsonType.ObjectId)] 
public string Id { get; set; } 

tiền phạt hoạt động

Nhưng trong khi Tôi đang kêu gọi bài phương pháp, nó đem lại cho tôi lỗi khác nhau

"'d05e139c-3a48-4213-bd89-eba0c22c3c6f' is not a valid 24 digit hex string." 

Làm thế nào có thể giải quyết vấn đề này

mẫu của tôi là:

public class EstablishmentDetails 
{ 

    [BsonRepresentation(BsonType.ObjectId)] 
    public string Id { get; set; } 
    public string EstablishmentName { get; set; } 
    public string EstablishmentType { get; set; } 
    public string Address { get; set; } 
    public string City { get; set; } 
    public int StateID { get; set; } 
    public Int32 PIN { get; set; } 
    public Int64 PhoneNumber { get; set; } 
    public string EmailID { get; set; } 
    public bool Published { get; set; } 
    public string CreatedDate { get; set; } 
    public string ModifiedDate { get; set; } 
} 

kho My fro Nhận phương pháp

public IEnumerable<EstablishmentDetails> GetAllEstablishmentDetails() 
    { 
     if (Convert.ToInt32(mCollection.Count()) > 0) 
     { 
      var EstablishmentDetailsCollection = mCollection.FindAllAs(typeof(EstablishmentDetails)); 

      if (EstablishmentDetailsCollection.Count() > 0) 
      { 
       foreach (EstablishmentDetails item in EstablishmentDetailsCollection) 
       { 
        establishmentDetails.Add(item); 
       } 
      } 
     } 
     var results = establishmentDetails.AsQueryable(); 
     return results; 
    } 

Kho lưu trữ của tôi cho phương thức Đăng

public EstablishmentDetails Add(EstablishmentDetails ed) 
    { 
     if (string.IsNullOrEmpty(ed.Id)) 
     { 
      ed.Id = Guid.NewGuid().ToString(); 
     } 

     mCollection.Save(ed); 
     return ed; 
    } 

Trả lời

3

Thay vì sử dụng

ed.Id = Guid.NewGuid().ToString(); 

tôi đã sử dụng

ed.Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString(); 

Đối tạo Id

của nó làm việc tốt:)

1

Guid.NewGuid() sẽ không tạo ObjectId. Object Id là 12 byte cấu trúc dữ liệu và Guid sản 16byte chuỗi hex (không có '-')

Bạn nên loại bỏ thuộc tính [BsonRepresentation(BsonType.ObjectId)]

Bạn có thể sử dụng bất kỳ chuỗi như Id trong tổ chức của bạn ví dụ 'HiDude' và bất kỳ chuỗi ở định dạng utf8.

Các vấn đề liên quan