尝试在 C# WebAPI 中从 MongoDb 获取所有记录时遇到错误
"Cannot deserialize string from BsonType ObjectId"
我的ID是
[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;
}
ed.Id = Guid.NewGuid().ToString();
我用过
ed.Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString();
用于生成Id
工作正常:)
您应该删除属性
[BsonRepresentation(BsonType.ObjectId)]
您可以在实体中使用任何字符串作为 Id,例如“HiDude”和任何 utf8 格式的字符串。
string
是适当的C#数据类型,但我不小心插入了一个文档(使用Studio3T>粘贴文档>导入文档)。我打算让它基于
_id
(一个简单的英语字符串值,如“ABC_123”;不是 GUID)更新现有文档。 但这不是粘贴文档的工作原理...如果导入的文档与现有文档有冲突的 _id,它将创建一个新的
ObjectId('...')
值,--并且与 C#
string
数据类型不兼容... 就我而言,由于我的意思是
update,而不是insert,所以我删除了额外的文档并正确进行了更新(a)删除并粘贴/导入,或者b)右键->单击“更新文档” )