为什么我在 .net 中检索 mongo 文档时出错?

Why am I getting Error retrieving mongo document in .net?

我已将文档插入 MongoDB

中的集合
public class Product :BaseDocument, IProduct
    {
        public Guid ProductId { get; set; }
        public string ProductName { get; set; }
        public Guid AccountId { get; set; }
        public List<IProductDetail> ProductDetailList { get; set; } = new List<IProductDetail>();
    }

public class ProductDetail:IProductDetail
        {
            public Guid ProductDetailId { get; set; }
            public string ProductDetailCode { get; set; }
        }

当我尝试检索它时,出现错误

public List<IProduct> GetProductsList(Guid accountId)
        {
            IEnumerable<IProduct> prodList = new List<Product>();
            IMongoCollection<Product> products = _database.GetCollection<Product>("Products");
            prodList = products.Find(m => m.AccountId == accountId).ToList();
            return prodList.ToList();
        }

错误如下

System.FormatException: 'An error occurred while deserializing the ProductDetailList property of class Entities.ProductDetail: Unknown discriminator value 'ProductDetail'.'

我做错了什么?

您收到此错误的原因是 MongoDB .NET 驱动程序不知道如何解析 IProductDetail,它会尝试实例化 ProductDetail class 因为有一个 _t 字段表示存储在 MongoDB 中的该类型。

通常你可以在那种 polymorphic scenario 中使用 BsonKnownTypes 但它只适用于 classes 和结构。所以如果你想在这里保留一些 class 层次结构,那么你需要引入一个抽象 class 并在那里应用这个属性。

[BsonKnownTypes(typeof(ProductDetail))]
public abstract class ProductDetailBase: IProductDetail
{
}

public class ProductDetail : ProductDetailBase
{
    public Guid ProductDetailId { get; set; }
    public string ProductDetailCode { get; set; }
}

然后你可以使用:

public List<ProductDetailBase> ProductDetailList { get; set; } = new List<ProductDetailBase>();

在这种情况下,您可以有一个 class 层次结构,并且 MongoDB .NET 驱动程序会在运行时将您的 BSON 文档反序列化为适当的子 class。