我正在尝试将嵌入对象插入、更新和删除(CRUD)到现有的 Monogodb 文档中,假设为客户添加多个地址,
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin",
"address": [
{
"building": "22 A, Indiana Apt",
"pincode": 123456,
"city": "Los Angeles",
"state": "California"
},
{
"building": "170 A, Acropolis Apt",
"pincode": 456789,
"city": "Chicago",
"state": "Illinois"
}
]
}
我可以使用命令行(添加多个地址)来完成,但是通过 mvc 核心,我只能在使用 InserOne 插入文档时插入单个地址,也可以使用 ReplaceOne 更新它,但我可以添加第二个或第三个地址。
这是我的 c# 类和接口(服务)
public class Customer
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("contact")]
[Required]
public string Contact { get; set; }
[BsonElement("dob")]
[Required]
public string Dob { get; set; }
[BsonElement("name")]
public string Name { get; set; }
public Addresses Address { get; set; }
}
public class Addresses
{
public string Building { get; set; }
public string Pincode { get; set; }
public string City { get; set; }
public string State { get; set; }
}
}
和服务
public Customer Create(Customer c)
{
customers.InsertOne(c);
return c;
}
public void Update(string id, Customer c)
{
customers.ReplaceOne(cutomer => cutomer.Id == id, c);
}