Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Entity Framework Core: Expression Must be Writeable

I'm using Entity Framework Core with MongoDB. However, I'm running into an issue when trying to use FirstOrDefault.

I have a base class, SignInCredentials:

public class SignInCredentials(string username, string? password)
{
    public string Username { get; set; } = username;
    public string? Password { get; protected init; } = password;
}

I extend it with Account:

public class Account : SignInCredentials
{
    // [Key] sets the primary key
    [Key]
    public ObjectId Id { get; private init; }

    private readonly byte[] salt;

    public Account(string username, string password) : base(username, null)
    {
        Id = new ObjectId();
        salt = GenerateSalt();
        Password = Hash(password, salt);
    }

    // More code not displayed
}

I store a DbSet<Account>, which is configured as: modelBuilder.Entity<Account>().ToCollection("accounts");

However, when I try: accounts.FirstOrDefault(a => a.Username == creds.Username);, where creds is a SignInCredentials, I get the following error:

System.ArgumentException: Expression must be writeable (Parameter 'left')
         at System.Linq.Expressions.Expression.RequiresCanWrite(Expression expression, String paramName)
         at System.Linq.Expressions.Expression.Assign(Expression left, Expression right)
         at System.Linq.Expressions.Expression.MakeBinary(ExpressionType binaryType, Expression left, Expression right, Boolean liftToNull, MethodInfo method, LambdaExpression conversion)
         at System.Linq.Expressions.BinaryExpression.Update(Expression left, LambdaExpression conversion, Expression right)
         at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
         at MongoDB.EntityFrameworkCore.Query.Visitors.ProjectionBindingRemovingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)

How do I fix this error?

like image 710
Rgamer43 Avatar asked Aug 29 '26 20:08

Rgamer43


1 Answers

A similar issue was reported: EfCore 8: Primitive collections in JSON documents error with init.

Either you should apply set rather than init.

public string? Password { get; protected set; } = password;

or you have to update the EF Core to 8.0.1 and above.

Note that: At this moment, MongoDB.EntityFrameworkCore (7.0) only supports EF Core 7 and .NET 7.

like image 94
Yong Shun Avatar answered Aug 31 '26 12:08

Yong Shun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!