skip to Main Content

I’m using Entity Framework with MongoDB. I have a class, Account with the following field:

private readonly byte[] salt;

Account is configured in Entity Framework like so:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Account>().ToCollection("accounts");
}

When I save an Account to my database, the corresponding document does not have salt.

How do I store a field or property in my database using Entity Framework whilst keeping it private?

2

Answers


  1. Chosen as BEST ANSWER

    Turns out I just needed to manually add the field for the model.

    var account = modelBuilder.Entity<Account>();
    account.Property("fieldName");
    account.ToCollection("accounts");
    

  2. You should implement a Backing Field.

    1. Configure Salt property with backing field: salt.
    internal class Account : SignInCredentials
    {
        private readonly byte[] salt;
    
        public byte[] Salt
        {
            get { return salt; }
        }
    
        ...
    }
    
    1. Configure the Salt with the backing field in Fluent API.
    internal class MongoDataContext : DbContext
    {
        ...
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity<Account>()
                .Property(x => x.Salt)
                .HasField("salt");
    
            modelBuilder.Entity<Account>()
                .ToCollection("accounts");
        }
    }
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search