首页 > 解决方案 > 当我在基类型中拥有另一个属性的 BsonId 属性时,有没有办法在派生类中使用“Id”属性?

问题描述

我可以在基类中使用 Id 属性,但是当我不想在派生类中执行此操作时,我会收到错误消息“'ConsoleApp1.DerivedWithId' 类型的属性 'Id' 不能使用元素名称 '_id'因为它已经被“ConsoleApp1.BaseWithoutId”类型的属性“IdForMongo”使用下面是一个控制台应用程序来说明

using System;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //This will work
            BsonClassMap.LookupClassMap(typeof(DerivedWithoutId));

            //But this will throw error: The property 'Id' of type 'ConsoleApp1.DerivedWithId' cannot use element name '_id' because it is already being used by property 'IdForMongo' of type 'ConsoleApp1.BaseWithoutId
            BsonClassMap.LookupClassMap(typeof(DerivedWithId));
        }
    }

    public class BaseWithoutId
    {
        [BsonId]
        public Guid IdForMongo{ get; set; }
    }

    public class BaseWithId
    {
        [BsonId]
        public Guid IdForMongo { get; set; }
        public Guid Id { get; set; }
    }

    public class DerivedWithId : BaseWithoutId
    {
        public Guid Id { get; set; }
        public string Description { get; set; }
    }

    public class DerivedWithoutId : BaseWithId
    {
        public string Description { get; set; }
    }
}

标签: c#mongodb

解决方案


我认为您可以在派生类中使用 [BsonNoId] 属性。

[BsonNoId]    
public class DerivedWithId : BaseWithoutId
{
    public Guid Id { get; set; }
    public string Description { get; set; }
}

推荐阅读