ORM implementations have several common ways of reflecting, paradigm, and code generation, either alone or in combination.
The paradigm of C # is very powerful, and when applied to an ORM, some features may seem more important.
When I first realized, I tried to write code as an ORM base class
namespace coat{public class ormbase<t> where T:class { ... public bool Update () { using (var conn = OpenConnection ()) { //beblow compile error, because Conn. Update<t> expect parameter to being T //i.e. The sub-class, but the ' this ' is the parent class. Return Conn. Update<t> (this);}}} The subclass generates similar code: public class User:ormbase<user> {...}
The intent is to implement the common methods of ActiveRecord object additions and deletions in the base class, which is more concise than implementing the corresponding code using code generation in a specific subclass. Also, editing an actual type is always easier than editing the template.
As a person who has played for two years without a paradigm (GO), I would think that a class User: ORMBase<User> { type declaration like C # is powerful.
The user type inherits from Ormbase, and type ormbase is using the user type as the paradigm parameter. This has no cyclic dependence?
In this way, ormbase can be used to do various programming with the Model T.
The above code is stuck in the conn.Update<T>(this); call of this sentence.
Because dapper's Update method signature Update<T>(T entityToUpdate) is similar, I wrote in Ormbase the this parent class, which is ormbase, and the type parameter T, passed in to update, is a subclass, say user.
The compiler immediately gave an error.
Ormbase and T is two different types, can not directly convert, write conn.Update<T>((T)this); compiler is also an error.
Some colleagues suggested modifying the ormbase update signature, and public bool Update(T obj) then sending obj instead of this to dapper.
This can solve the compilation problem, but will make the application call time-varying trouble, rather than directly to the Update method to move the subclass inside the generated, but still not beautiful.
Studied the paradigm constraints and found a more beautiful way.
Ormbase and T cannot be converted because the compiler does not know the inheritance relationship between them, and writes their inheritance to the paradigm constraint and can be converted.
public class RecordBase<T> where T : RecordBase<T>
This declares that the constraint T must be a RecordBase<T> subclass of, and the Update method instead:
return conn.Update<T>((T)this);
will be able to compile successfully.
Although it can be compiled, but here is the conversion of the parent class to subclass, how can be successfully compiled, I actually have to understand the details of wood.
Some friends know, also hope to inform.
Thank you.
Development Note 1: Fan type