Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MongoDB Field mapping

Tags:

c#

mongodb

I have the following setup that works but when the MongoDB Collection has extra field then the program crash with error

"System.FormatException: Element 'FriendName' does not match any field or property of class MyApp.User"

I am under the impression that the MongoDB driver is able to map only the fields that is declared in C# Class. Is there a way around this ? Thank you.

MongoDB - Collection User

{ Name: "Allen" , Age: 22, Address: "Sample Address", FriendName = "Sue"}


public class User
{
  public string Name {get;set;}
  public int Age {get; set;}
  public string Address {get;set; }
}


 _db.GetCollection<User>("User").Find(f => f.Name == "Allen").FirstOrDefault();
like image 630
AlbertK Avatar asked Sep 10 '26 00:09

AlbertK


2 Answers

MongoDB C# driver expects that all fields in your BSON document match your .NET class - that's the default behavior. You can change that using BsonIgnoreExtraElements attribute

[BsonIgnoreExtraElements]
public class User
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}
like image 130
mickl Avatar answered Sep 11 '26 15:09

mickl


I also found a way to globally set the BsonIgnoreExtraElements by call the following ConventionPack before accessing the DB.

 var conventionpack = new ConventionPack() { new IgnoreExtraElementsConvention(true) };
 ConventionRegistry.Register("IgnoreExtraElements", conventionpack, type => true);
like image 38
AlbertK Avatar answered Sep 11 '26 15:09

AlbertK