mongoDb数据库如何尊重清洁代码架构?

J4N*_*J4N 5 c# repository-pattern mongodb .net-core clean-architecture

我正在设置一个 C# Asp.Net Core Api,它将在未来大幅增长。因此,我试图尊重干净代码架构,以我的域为中心,没有任何依赖性和周围的一切:

public abstract class Entity
{
    public Guid Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我目前正在实施存储库。我的问题是,对于 mongoDb,似乎必须提供属性[BsonId],或者在我的实体中使用 BsonId。但这意味着在我的实体项目中添加 mongoDb 引用,我不是它的忠实粉丝。

public interface IRepository<TDocument> where TDocument : Entity
{
    IQueryable<TDocument> AsQueryable();
    IEnumerable<TDocument> FilterBy(
        Expression<Func<TDocument, bool>> filterExpression);
    IEnumerable<TProjected> FilterBy<TProjected>(
        Expression<Func<TDocument, bool>> filterExpression,
        Expression<Func<TDocument, TProjected>> projectionExpression);
    Task<TDocument> FindOne(Expression<Func<TDocument, bool>> filterExpression);

    Task<TDocument> FindById(Guid id);
    Task InsertOne(TDocument document);
    Task InsertMany(ICollection<TDocument> documents);
    Task ReplaceOne(TDocument document);
    Task DeleteOne(Expression<Func<TDocument, bool>> filterExpression);
    Task DeleteById(Guid id);
    Task DeleteMany(Expression<Func<TDocument, bool>> filterExpression);
}
Run Code Online (Sandbox Code Playgroud)

在我在 Clean Architecture 上找到的示例中,他们大多使用实体框架,不需要绝对属性即可工作。

我可以想象做另一个类并使用 AutoMapper 在彼此之间进行映射,但这似乎很麻烦,因为我总是想保留业务对象中的所有内容,这可能会导致一些错误。

是否有一种方法可以指示每个集合(甚至全局)存储库中或保存时的 Id 是什么?

Zar*_*Zar 4

您可以使用“BsonClassMap”:

BsonClassMap.RegisterClassMap<SomeEntity>(cm =>
        {
            cm.AutoMap();
            cm.SetIgnoreExtraElements(true);
            cm.MapIdMember(c => c.Id);
        });
Run Code Online (Sandbox Code Playgroud)

参考:https ://mongodb.github.io/mongo-csharp-driver/2.14/reference/bson/mapping/