The last one talked about the official MongoDB-driven query function, this time to say the official drive to delete and change function, the driver after upgrading to 2.0, the corresponding insert,update and delete are only the asynchronous version (or called parallel version), This is certainly followed by. NET go the positive direction, the big things, but sometimes, our front desk has been implemented using synchronization, in order not to change the foreground code, so, the background of the asynchronous version may not be what we need, so we need to do some transformation, the asynchronous to synchronize, that is, the main thread waits for the asynchronous method to execute, Code, so that the correctness of the method can be ensured.
Since Insert,update,delete is going to do this kind of wait, extract it into a method
/// <SUMMARY> /// wait for the task to finish before returning to /// </summary> /// <param name= " Func "></PARAM> /// < Returns></returns> private Task forwait (func<task>< Span style= "color: #000000;" > Func) { var t = Func (); T.wait (); return T; }
The following is an official driver implementation of insert,update and delete, and the method signature does not expose MONGO, which is a good thing for developers, so let's look at the code
PublicTask Insertasync (TEntity item) {returnForwait (() =_table. Insertoneasync (item)); } PublicTask Deleteasync (TEntity item) {varquery =NewQuerydocument ("_id",NewObjectId (typeof(TEntity). GetProperty (EntityKey). GetValue (item). ToString ())); returnForwait (() =_table. Deleteoneasync (query)); } PublicTask Updateasync (TEntity item) {varquery =NewQuerydocument ("_id",NewObjectId (typeof(TEntity). GetProperty (EntityKey). GetValue (item). ToString ())); varFieldList =NewList<updatedefinition<tentity>>(); foreach(varPropertyinch typeof(TEntity). GetProperties (BindingFlags.Instance |bindingflags.public)) {if(property. Name! = EntityKey)//The update set cannot have entity keys _id{fieldlist.add (Builders<TEntity>. Update.set (property. Name, property. GetValue (item))); } } returnForwait (() = _table. Updateoneasync (Query, builders<tentity>. Update.combine (FieldList))); }
The corresponding, synchronous method calls the Async method directly (now it's just a pseudo-async)
Public void Insert (TEntity Item) { Insertasync (item); } Public void Delete (TEntity Item) { Deleteasync (item); } Public void Update (TEntity Item) { Updateasync (item); }
For the business layer to invoke it, there is no difference between the previous EF architecture and the Redis architecture, so you can dynamically switch these persistent methods through the IOC! Each play and self-advantage!
This is: Eight Immortals crossing, recount!
MongoDB Learning Notes ~ added additions and deletions to the Imongorepository interface for the official drive