我有一个DocumentDb
数据库的存储库。我的文档都有一组共同属性,所以所有文档都实现了IDocumentEntity接口。是否有可能在C#中有额外的(忽略)属性?
public interface IDocumentEntity {
[JsonProperty("id")]
Guid Id { get; set; }
[JsonProperty("documentClassification")]
DocumentClassification DocumentClassification { get; set; }
}
public class KnownDocument : IDocumentEntity {
[JsonProperty("id")]
Guid Id { get; set; }
[JsonProperty("documentClassification")]
DocumentClassification DocumentClassification { get; set; }
[JsonProperty("knownProperty")]
string KnownProperty { get; set; }
}
public class BaseDocumentRepository<T> where T : IDocumentEntity {
public Set(T entity) {
// ... stuff
}
}
这工作正常与KnownDocument
我知道所有的属性。但是,当然,对于一个Document Db来说最棒的是我不需要知道所有的属性(并且在很多情况下我不会)。
所以我的客户端提交有点像这个 -
{unknownProperty1: 1, unknownProperty2: 2}
而且我想这UPSERT使用我的文档库。
public OtherDocumentService() {
_otherDocumentService = new OtherDocumentRepository();
}
public UpsertDocument(dynamic entity) {
entity.id = new Guid();
entity.documentClassification = DocumentClassification.Other;
_otherDocumentRepository.Set(entity);
}
,但我得到一个InvalidCastException从dynamic
到IDocumentEntity
。我认为这是因为动态对象上存在的额外属性,但不在IDocumentEntity
接口上?
我想要做的事情是让我的文档实体处于动态状态,但依靠一些属性来维护它们。
这是不幸的,但似乎是它必须要走的路 –