【发布时间】:2020-11-12 12:45:11
【问题描述】:
我正在使用 c# mongo db 驱动程序来插入和更新文档。首先我插入一条记录,然后我尝试使用 FindOneAndUpdateAsync 方法更新特定的记录字段。我能够正确更新它,但更新后我收到错误“缺少类 SampleApp.Person 的属性‘名称’的必需元素‘名称’。”我使用的是 MongoCommunity 版本 4.4.1,而 mongo 驱动程序是 2.11.4。
我的收藏结构是
[BsonSerializer(typeof(ImpliedImplementationInterfaceSerializer<IPerson, Person>))]
public interface IPerson
{
string Id { get; set; }
string Name { get; set; }
int Age { get; set; }
string Email { get; set; }
IAddress Address { get; set; }
bool IsActive { get; set; }
}
public class Person : IPerson
{
[BsonId]
public string Id { get; set; }
[BsonRequired]
public string Name { get; set; }
[BsonRequired]
public int Age { get; set; }
public string Email { get; set; }
public IAddress Address { get; set; }
[BsonRequired]
public bool IsActive { get; set; }
}
public interface IAddress
{
string Line1 { get; set; }
string Line2 { get; set; }
string Line3 { get; set; }
string City { get; set; }
string State { get; set; }
string Pincode { get; set; }
}
public class Address : IAddress
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Pincode { get; set; }
}
我的插入和更新代码如下所示。
MongoClient client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
BsonClassMap.RegisterClassMap<Address>();
var peopleCollection = database.GetCollection<IPerson>("People");
IPerson person = new Person()
{
Age = 50,
Email = "a@a.com",
IsActive = false,
Name = "David",
Id = ObjectId.GenerateNewId().ToString()
};
try
{
await peopleCollection.InsertOneAsync(person);
IAddress address = new Address()
{
City = "Bengaluru",
Line1 = "Bengaluru",
Line2 = "Bengaluru",
Line3 = "Bengaluru",
Pincode = "560001",
State = "KA"
};
var updateDefinition = Builders<IPerson>.Update.Set(x => x.Address, address).Set(x =>
x.IsActive, true);
var filter = Builders<IPerson>.Filter.Eq(x => x.Email, "a@a.com");
FindOneAndUpdateOptions<IPerson> updateOptions = new FindOneAndUpdateOptions<IPerson>
{
IsUpsert = false,
ReturnDocument = ReturnDocument.After,
Projection = Builders<IPerson>.Projection.Include(c => c.Address)
};
IPerson updatedPerson = await peopleCollection.FindOneAndUpdateAsync(filter, updateDefinition, updateOptions);
}
catch (Exception ex)
{
string s = ex.Message;
Console.WriteLine(s);
}
【问题讨论】:
-
类中的属性需要公开才能使序列化工作。
-
您是否尝试过删除
[BsonRequired]并查看您得到的回复?错误是说无论检索到什么值,它都缺少Name属性。
标签: c# mongodb mongodb-query mongodb-.net-driver mongodb-csharp-2.0