Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我必须提供私有setter来自动映射使用构造函数的派生类?_C#_Mongodb - Fatal编程技术网

C# 为什么我必须提供私有setter来自动映射使用构造函数的派生类?

C# 为什么我必须提供私有setter来自动映射使用构造函数的派生类?,c#,mongodb,C#,Mongodb,我正在尝试使用MongoDb的C#驱动程序注册类映射。在我的例子中,我有许多从基类派生的类。所有的构造函数都需要参数,并且它们的属性都是get only。有趣的是,MongoDb在映射此类派生类时会抛出一个错误,除非其属性至少有一个私有setter 有关在启动配置期间发生的异常的再现方法,请参见下文: public class Base { public Base(int myBaseProperty) {

我正在尝试使用MongoDb的C#驱动程序注册类映射。在我的例子中,我有许多从基类派生的类。所有的构造函数都需要参数,并且它们的属性都是get only。有趣的是,MongoDb在映射此类派生类时会抛出一个错误,除非其属性至少有一个私有setter

有关在启动配置期间发生的异常的再现方法,请参见下文:

        public class Base
        {
            public Base(int myBaseProperty)
            {
                MyBaseProperty = myBaseProperty;
            }

            public int MyBaseProperty { get; }
        }

        public class Derived : Base
        {
            public Derived(int myBaseProperty, string myDerivedProperty) : base(myBaseProperty)
            {
                MyDerivedProperty = myDerivedProperty;
            }

            public string MyDerivedProperty { get; }
        }

        public class DerivedWithSetter : Base
        {
            public DerivedWithSetter(int myBaseProperty, string myDerivedProperty) : base(myBaseProperty)
            {
                MyDerivedProperty = myDerivedProperty;
            }

            public string MyDerivedProperty { get; private set; }
        }

**IN STARTUP**

            BsonClassMap.RegisterClassMap<Base>(cm =>
            {
                cm.AutoMap();
                cm.MapCreator(b => new Base(b.MyBaseProperty));
            });

            BsonClassMap.RegisterClassMap<DerivedWithSetter>(cm =>
            {
                cm.AutoMap();
                cm.MapCreator(d => new DerivedWithSetter(d.MyBaseProperty, d.MyDerivedProperty));
            });

            BsonClassMap.RegisterClassMap<Derived>(cm =>
            {
                cm.AutoMap();
                cm.MapCreator(d => new Derived(d.MyBaseProperty, d.MyDerivedProperty));
            });
这里,文本值
2
被传递给基构造函数,而不是参数
int myBaseProperty
。在这种情况下,也不例外。这可能表明它与MongoDb在自动映射属性时如何评估派生类的构造函数有关。添加私有setter可能只是通过允许MongoDb完全绕过构造函数来“解决”问题。这是预期的行为,还是MongoDb假设能够通过构造函数以这种方式自动映射

            public Derived(string myDerivedProperty) : base(2)
            {
                MyDerivedProperty = myDerivedProperty;
            }