[EF-95] Unable to cast object of type 'MongoDB.Bson.BsonNull' to type 'MongoDB.Bson.BsonDocument' Created: 07/Feb/24  Updated: 07/Feb/24

Status: Needs Triage
Project: Entity Framework
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Unknown
Reporter: Rajesh Dammu Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: c#
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Dotnet Drivers

 Description   

Problem Statment: Issue with mapping null to Object. In below example I have User class with an Address (can be null).  Saving User without Address, and reading the Document from Mongo throws and exception.

 

C# class

using MongoDB.Bson.Serialization.Attributes;
 
 
[BsonIgnoreExtraElements]
public class User
{
     public User()
    {
        Version = Guid.NewGuid();
    }
    [BsonId]
    public Guid Id { get; set; }
    public Guid Version { get; set; }
     public string FirstName { get; set; }
     public Address address { get; set; } // can be null
}
 
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

Create User object without Address and retrieve user throws an excepiton.

 User user = new User();
 user.FirstName= "Scott";
 // add user to context
 _context.User.Add(user);
 // save changes
 _context.SaveChanges();
 
 // read user
* // throws exception as unable to cast null to address*
 var item = _context.User.FirstOrDefault(x => x.FirstName == "Scott");

DB Context class

public class MongoDBContext : DbContext
{
    public DbSet<User> User { get; init; }
 
    public static MongoDBContext Create(IMongoDatabase database) =>
        new(new DbContextOptionsBuilder<MongoDBContext>()
            .UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName)
            .Options);
 
    public MongoDBContext(DbContextOptions options)
        : base(options)
    {
 
    }
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
 
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<User>().ToCollection("user");
    }
 
    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        configurationBuilder.Conventions.Add(d =>
        new CamelCasePropertyNameConvention(d.GetService<ProviderConventionSetBuilderDependencies>()!));
        base.ConfigureConventions(configurationBuilder);
    }
}


Generated at Thu Feb 08 08:26:54 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.