Search code examples
c#mongodbmongodb-.net-driver

MongoDb collection Name different from C# class


This is our C# generic Class.

public class CustomerQuoteDetails<T> :BaseClass {
    [BsonId(IdGenerator = typeof(UniqueIdGenerator))]
    public string QuoteDetailId { get; set; }
    public string Title { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string ContactNo { get; set; }
    public DateTime DOB { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string Token { get; set; }
    public string ProfilePicture { get; set; }
    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime TokenCreatedOn { get; set; }
    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime LastLoginTime { get; set; }
    public List<T> Answers { get; set; }       
}

And this is document which is generated by our class.

{ 
    "_id" : "053ab8f1-ceda-49a7-ab7a-0dce034b4c20", 
    "CreatedBy" : "", 
    "CreatedDate" : ISODate("2019-10-04T04:52:44.313+0000"), 
    "UpdatedBy" : "", 
    "UpdatedDate" : ISODate("2019-10-04T04:52:44.314+0000"), 
    "IsDeleted" : false, 
    "Title" : "Mr", 
    "FirstName" : "", 
    "LastName" : "", 
    "ContactNo" : "", 
    "DOB" : ISODate("2019-10-04T04:52:44.314+0000"), 
    "Email" : "a@a.com", 
    "Password" : null, 
    "Token" : "7e396637-e8b2-4c1c-badb-cc14d785b03d", 
    "ProfilePicture" : null, 
    "TokenCreatedOn" : ISODate("2019-10-04T04:52:44.314+0000"), 
    "LastLoginTime" : ISODate("2019-10-04T04:52:44.314+0000"), 
    "Answers" : [

    ],     
}

The problem is we want to name the collection as CustomerQuoteDetails but it is naming it CustomerQuoteDetails`1 due to generic class. Is there any way that I can name my collection as I want?


Solution

  • Why not just introduce a property that allows you to set the collection name ? Based on your comment I cant really tell where you call the your GetCollection(), in your base class in some repository or wherever.

    But nothing is stopping you from perhaps implementing a virtual property called CollectionName on your BaseClass and overriding it in your CustomerQuoteDetails class and doing something like _mongoDbContext.GetCollection<TEntity>(customerQuoteDetails.CollectionName); Or introducing a constants class that encompasses your collection names . Perhaps update your answer to include where you do the GetCollection().