BsonElement属性和MongoDB C#驱动程序的自定义反序列化逻辑 [英] BsonElement attribute and custom deserialization logic with MongoDB C# driver
问题描述
请考虑以下示例:
public class Foo
{
private string _text;
[BsonElement("text"), BsonRequired]
public string Text
{
get { return _text; }
set
{
_text = value;
Bar(_text);
}
}
private void Bar(string text)
{
//Only relevant when Text is set by the user of the class,
//not during deserialization
}
}
Text
属性的设置器,以及随后的Bar
方法,在类的用户为属性分配新值时以及在MongoDB C#驱动程序反序列化对象期间均被调用.我需要确保仅当用户设置了Text
属性时才调用Bar
,而不是在反序列化期间调用.
The setter of the Text
property and, subsequently, the method Bar
are called both when the user of the class assigns a new value to the property and during object deserialization by the MongoDB C# driver. What I need is to ensure that Bar
is called only when the Text
property is set by the user and not during deserialization.
我看到了两种不太适合我的解决方案:
I see two solutions which don't really suit me:
第一个是将BsonElement
属性移动到后备字段.但是,据我所知,MongoDB C#驱动程序在查询构建中使用了BsonElement
属性,因此我将失去在查询中使用Text
属性的能力.
The first is to move the BsonElement
attribute to the backing field. However, as far as I know, the BsonElement
attribute is used in query building by the MongoDB C# driver, so I will lose the ability to use the Text
property in queries.
第二种解决方案是将Text
设置器设为私有,并添加一个方法,该类的用户将通过该方法设置Text
属性,并在其中调用Bar
方法.但是,在现有解决方案中经常使用Text
设置器,我有点不愿意在所有文件中更改70个以上的调用.另外,代码的可读性也会降低.
The second solution is to make the Text
setter private and add a method through which the user of the class will set the Text
property, and in which the Bar
method would be called. However, the Text
setter is used very often in the existing solution, and I'm a bit reluctant to change 70+ calls across all files. Plus, the code will become less readable.
在保留属性上的BsonElement
属性的同时,有没有更干净的方法来分离反序列化和用户提示的属性更改?
Is there any cleaner way to separate deserialization and user-prompted property change while retaining the BsonElement
attribute on the property?
推荐答案
为什么不为用户和数据库为同一私有变量创建单独的属性,就像这样,
Why not create a seperate property for the users and for the DB for the same private variable, something like this,
public class Foo
{
private string _text;
[BsonElement("text"), BsonRequired]
public string TextDB
{
get { return _text; }
set
{
_text = value;
}
}
[BsonIgnore]
public string Text
{
get { return _text; }
set
{
_text = value;
Bar(_text);
}
}
private void Bar(string text)
{
//Only relevant when Text is set by the user of the class,
//not during deserialization
}
}
这篇关于BsonElement属性和MongoDB C#驱动程序的自定义反序列化逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!