Strange bheaviuor with derived class
See original GitHub issueAs stated in the title, i see a strange behaviour when try to save a derived type. Not clear if it’s a bug or a “feature” inherited from MongoDB driver, but it’s at least misleading in some situation, and accordingly with what is written in documentation.
Here the example :
Person model = Person.BuildModel_Simple();
Random rng = new Random();
model.Name += rng.Next(10000, 99999).ToString();
var task = MongoDB.Entities.DB.SaveAsync<Entity>(model);
task.Wait();
var result = task.Result;
Assert.IsTrue(result?.UpsertedId != null);
And here the definition of Person
[Name("Person")]
public class Person : Entity, ICreatedOn, IModifiedOn
{
public string Name { get; set; }
public string Surname { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public override string GenerateNewID()
=> $"{(this.Name ?? "").Trim()}{(this.Surname ?? "").Trim()}".ToSubSHA256();
}
Now accordingly to the configuration i have set the entity name ( named “Person”) so when i save it, a collection named “Person” should created regardeless of the type.
But if my saving command is :
var task = MongoDB.Entities.DB.SaveAsync<Entity>(model);
Then the collection is named Entity :
If i change the save command to :
var task = MongoDB.Entities.DB.SaveAsync<Person>(model);
everything working fine
Mistery in the mistery i see a new property (in the mongo document) named _t that refer the correct type/name. A bit confused on what’s going on.
My goal is to save derived type in different collection.
Ps : i have now noticed that when i save thorugh the “Entity” (the faulty one) version of the command the CreatedOn and ModificedOn property are not considered. That part is handled in that library (MongoDB.Entities) so this let me suppose that somewhere in the library code, the generic type of SaveAsync method is checked instead of the type of the actual instance provided.
PPs : after a bit of digging in the library code here my suspected line of code
in yellow the problem about date in azure the problem about the attribute
It’s not clear to me (but i have to admit that i have not completley clear the architecture) why cache work on the generic type and not over instance type
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
I agree with @dj-nitehawk
my opinion is that the exact type should be used in the api explicitly (or via inference). By allowing DB.SaveAsync< Entity >() would introduce messy usage patterns and would require reflection that can be avoided by just specifying the correct type.
Ok thanks for tips, i’ll keep in mind for future post