-
Type: Bug
-
Resolution: Duplicate
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Dotnet Drivers
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); } }
- duplicates
-
EF-90 Mapping nullable Lists into Models
- Closed