我在尝试从C#WebAPI获取MongoDb的所有记录时收到错误"Cannot deserialize string from BsonType ObjectId"
我的身份证明
[BsonId]
public string Id { get; set; }
将其更改为
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
工作正常
但是当我正在调用post方法时,它给了我不同的错误
"'d05e139c-3a48-4213-bd89-eba0c22c3c6f' is not a valid 24 digit hex string."
如何解决这个问题
我的模特是:
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; }
}
我的存储库来自Get方法
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;
}
我的Post方法库
public EstablishmentDetails Add(EstablishmentDetails ed)
{
if (string.IsNullOrEmpty(ed.Id))
{
ed.Id = Guid.NewGuid().ToString();
}
mCollection.Save(ed);
return ed;
}
答案 0 :(得分:10)
而不是使用
ed.Id = Guid.NewGuid().ToString();
我用过
ed.Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString();
用于生成Id
它的工作正常:)
答案 1 :(得分:2)
Guid.NewGuid()不会产生ObjectId。 对象ID是12字节数据结构,Guid产生16字节十六进制字符串(没有&#39; - &#39;)
您应该删除属性[BsonRepresentation(BsonType.ObjectId)]
您可以在实体中使用任何字符串作为ID,例如&#39; HiDude&#39;以及utf8格式的任何字符串。