0

我一直在尝试保留一个名为 User 的具体类,它继承了 Entity。我不明白为什么 Id 与数据库和调试代码不同。我将 C# 与 MongoDb.Driver 一起使用。

public abstract class Entity : IEntity
{
    public Guid Id { get; protected set; }
    public string Description { get; protected set; }
}

public class User : Entity
{
    public string Issuer { get; protected set; }
    public string Subject { get; protected set; }
    public IEnumerable<string> Roles { get; protected set; }

    public User(string issuer, string subject, IEnumerable<string> roles = null)
    {
        Issuer = issuer;
        Subject = subject;
        Roles = roles;
    }
}

作为参考,这是我的存储库及其保存方法。

public class UserRepository
{
    private readonly string _connectionString;
    private readonly string _databaseName;

    protected string CollectionName => "user";

    protected RepositoryAbstract(IMongoStorageConnection mongoStorageConnection)
    {
        _connectionString = mongoStorageConnection.ConnectionString;
        _databaseName = mongoStorageConnection.DatabaseName;
    }

    protected IMongoQueryable<User> MongoCollectionQuery => MongoCollection.AsQueryable();

    protected IMongoCollection<User> MongoCollection => MongoDatabase.GetCollection<User>(CollectionName);

    private IMongoDatabase MongoDatabase => MongoClient.GetDatabase(_databaseName);

    private MongoClient MongoClient
    {
        get
        {
            MongoUrl mongoUrl = new MongoUrl(_connectionString);

            MongoClientSettings settings = MongoClientSettings.FromUrl(mongoUrl);
            settings.SslSettings = new SslSettings
            {
                EnabledSslProtocols = SslProtocols.Tls12
            };

            MongoClient mongoClient = new MongoClient(settings);
            return mongoClient;
        }
    }

    public async Task SaveAsync(User entity) => await MongoCollection.InsertOneAsync(entity);
}

当我尝试将用户保存到数据库时,存储在数据库中的 _id 字段与我的代码中显示的 ID 不同。

从数据库查看

从代码查看

谁能解释为什么?

4

0 回答 0