当我具有基本类型的另一个属性的BsonId属性时,是否可以在派生类中使用“ Id”属性?

问题描述 投票:2回答:1

我可以在基类中使用一个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
1个回答
2
投票

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

[BsonNoId]    
public class DerivedWithId : BaseWithoutId
{
    public Guid Id { get; set; }
    public string Description { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.